unit Unit1; 

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
  Menus, ExtCtrls, Grids, Buttons, StdCtrls, Spin, PReport, uCmdBox,
  libusb, INIFiles, mmsystem;

type
  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    CalibCurrentBox: TCheckBox;
    CalibVoltageBox: TCheckBox;
    CheckGroup1: TCheckGroup;
    CmdBox: TCmdBox;
    CurrentCorrHGrid: TStringGrid;
    CurrentOffsetHBiGrid: TStringGrid;
    CurrentOffsetLUniGrid: TStringGrid;
    CurrentGlass: TLabel;
    CurrentCorrLGrid: TStringGrid;
    CurrentLabel: TLabel;
    CurrentOffsetLBiGrid: TStringGrid;
    CurrentOffsetHUniGrid: TStringGrid;
    CurrentRefLabel: TLabel;
    CurrentVerifyGrid: TStringGrid;
    UCVccLabel: TLabel;
    VccLabel: TLabel;
    GenerateReportBox: TCheckBox;
    GlassSetBtn: TButton;
    GlassVoltageEdit: TFloatSpinEdit;
    GroupBox1: TGroupBox;
    GroupBox2: TGroupBox;
    GroupBox3: TGroupBox;
    GroupBox4: TGroupBox;
    GroupBox5: TGroupBox;
    GroupBox6: TGroupBox;
    GroupBox7: TGroupBox;
    GroupBox8: TGroupBox;
    HardVerEdit: TSpinEdit;
    KorPradLEdit: TSpinEdit;
    Label1: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    Label13: TLabel;
    Label14: TLabel;
    Label15: TLabel;
    Label16: TLabel;
    Label18: TLabel;
    Label17: TLabel;
    Label19: TLabel;
    Label20: TLabel;
    Label21: TLabel;
    VoltageCorrLabel: TLabel;
    Label2: TLabel;
    CurrentCorrLLabel: TLabel;
    CurrentOffsetLUniLabel: TLabel;
    CurrentOffsetLBiLabel: TLabel;
    CurrentCorrHLabel: TLabel;
    CurrentOffsetHUniLabel: TLabel;
    CurrentOffsetHBiLabel: TLabel;
    FreqLabel: TLabel;
    VoltageOffsetLabel: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Label7: TLabel;
    Label8: TLabel;
    Label9: TLabel;
    MainMenu1: TMainMenu;
    MenuItem1: TMenuItem;
    Help: TMenuItem;
    MenuItem2: TMenuItem;
    ModNumberEdit: TSpinEdit;
    KorPradHEdit: TSpinEdit;
    OffsetPradHUniEdit: TSpinEdit;
    OffsetPradHBiEdit: TSpinEdit;
    OffsetPradLUniEdit: TSpinEdit;
    OffsetPradLBiEdit: TSpinEdit;
    PageControl1: TPageControl;
    KorNapEdit: TSpinEdit;
    OffsetNapEdit: TSpinEdit;
    UseKorNapBox: TCheckBox;
    ReportPDF: TPReport;
    ProdDateEdit: TSpinEdit;
    ProgramFlashBox: TCheckBox;
    RadioButton1: TRadioButton;
    RadioButton2: TRadioButton;
    RadioButton3: TRadioButton;
    RadioGroup1: TRadioGroup;
    ShuntCurrentEdit: TSpinEdit;
    ShuntVoltageEdit: TSpinEdit;
    StatusBar1: TStatusBar;
    StringGrid1: TStringGrid;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    TabSheet3: TTabSheet;
    TabSheet4: TTabSheet;
    TabSheet5: TTabSheet;
    TrayIconDisconnected: TTrayIcon;
    TrayIconConnected: TTrayIcon;
    UseOffsetNapBox: TCheckBox;
    UseKorPradHBox: TCheckBox;
    UseKorPradLBox: TCheckBox;
    UseOffsetPradHUniBox: TCheckBox;
    UseOffsetPradHBiBox: TCheckBox;
    UseOffsetPradLUniBox: TCheckBox;
    UseOffsetPradLBiBox: TCheckBox;
    VerifyBox: TCheckBox;
    VoltageCorrGrid: TStringGrid;
    VoltageGlass: TLabel;
    VoltageLabel: TLabel;
    VoltageOffsetGrid: TStringGrid;
    VoltageRefLabel: TLabel;
    VoltageVerifyGrid: TStringGrid;
    ZeroMaleICheckbox: TCheckBox;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure CalibCurrentBoxChange(Sender: TObject);
    procedure CalibVoltageBoxChange(Sender: TObject);
    procedure CmdBoxClick(Sender: TObject);
    procedure GenerateReportBoxChange(Sender: TObject);
    procedure GlassSetBtnClick(Sender: TObject);
    procedure CmdBoxInput(ACmdBox: TCmdBox; Input: string);
    procedure FormCreate(Sender: TObject);
    procedure HardVerEditEditingDone(Sender: TObject);
    procedure MenuItem2Click(Sender: TObject);
    procedure ModNumberEditChange(Sender: TObject);
    procedure ModNumberEditEditingDone(Sender: TObject);
    function OpenUsb:Boolean;
    procedure CloseUsb;
    procedure ProdDateEditEditingDone(Sender: TObject);
    procedure ProgramFlashBoxChange(Sender: TObject);
    procedure RadioButton1Change(Sender: TObject);
    procedure RadioButton2Change(Sender: TObject);
    procedure RadioButton3Change(Sender: TObject);
    procedure ShuntCurrentEditEditingDone(Sender: TObject);
    procedure ShuntVoltageEditEditingDone(Sender: TObject);
    procedure StringGrid1ValidateEntry(sender: TObject; aCol, aRow: Integer;
      const OldValue: string; var NewValue: String);
    procedure VerifyBoxChange(Sender: TObject);
    procedure ZeroMaleICheckboxChange(Sender: TObject);
    procedure GenerateReport;
  private
    { private declarations }
  public
    { public declarations }
  end;

type
  THvmSettings = packed record
    NrModHVM: Word;
    Rezerwa: Word;
    HardVer: Word;
    ZeroMaleI: Byte;
    KorMul_PradL: ShortInt;
    TypBocz_Prad: Word;
    TypBocz_Nap: Byte;
    Interwal: Byte;   //0,1,2
    //Kalibracja
    Offset_Pom_Nap: ShortInt;  //<-30,30>
    Offset_Pom_PradL_Bi: ShortInt; //<-30,30>
    Offset_Pom_PradL_Uni: ShortInt;//<-30,30>
    Offset_Pom_PradH_Bi: ShortInt; //<-30,30>
    Offset_Pom_PradH_Uni: ShortInt; //<-30,30>

    KorMul_Pom_Nap: ShortInt;  //<-10,10>
    KorMul_PradH: ShortInt;

    HVM_DataKalibr: LongWord;
    HVM_DataProd: LongWord;

    EE_CrcKalibr: Word;
  end;
type
  THvmMeas = packed record
    voltage: Word;
    voltage_r: Byte;
    current: Word;
    current_r: Byte;
    energyIn: LongWord;
    energyIn_r: Byte;
    energyOut: LongWord;
    energyOut_r: Byte;
    time: LongWord;
    eventIndex: Word;
    errStat: Byte;
    energyAvg: LongWord;
    energyAvg_r: Byte;
  end;
type
  THvmInfo = packed record
    HardVer: Byte;
    SoftVer: Byte;
    RPomIU: Byte;
    NrHvm: Word;
    DTContrMetr: LongWord;
    TypBocz_PradL: Byte;
    TypBocz_PradH: Byte;
    TypBocz_Nap: Byte;
    DTProd: LongWord;
    HvmRstStatusErr: Byte;
    HvmRstStatusTmp: Byte;
    Interval: Byte;
  end;
type
  THvmEvent = packed record
    hvmIndex: Word;
    eventType: Byte;
    time: LongWord;
    energyIn: LongWord;
    energyIn_r: Byte;
    energyOut: LongWord;
    energyOut_r: Byte;
    eventIndex: Word;
    reserve: Word;
    hvmStat: Byte;
    pos: Array[0..9] of Byte;
    eventCrc: Word;
  end;
type
  TTesterOutputs = packed record
    polarity:Byte;
    hvEnabled: Byte;
    glassVoltage: Word;
    glassCurrent: Word;
    currentA: LongWord;
    currentB: LongWord;
  end;
type
  TAnalogInputs = packed record
    UCVcc: Word;
    Vcc: Word;
    Ref2: Word;
    Prad1: Word;
    Prad2: Word;
    Dziel: Word;
    Nap: Word;
    Prl: Word;
    Prh: Word;
    M5v: Word;
  end;
type
  TStatus = packed record
    State: LongWord;
    Voltage: LongInt;
    Current: LongInt;
    VoltageRef: LongInt;
    CurrentRef: LongInt;
    VoltageGlass: Word;
    CurrentGlass: Word;
    Freq: Word;
    AnalogInputs: TAnalogInputs;
  end;
type
  TTesterState = packed record
    Status:TStatus;
    HvmSettings: THvmSettings;
    HvmMeas: THvmMeas;
    HvmInfo: THvmInfo;
    HvmEvent: THvmEvent;
    TesterOutputs:TTesterOutputs;
  end;

type

  RecvThread = class(TThread)
  private
    newLine:PChar;
    newString:String;
    end_index:LongInt;
    procedure WriteConsole;
  protected
    procedure Execute; override;
  public
    Constructor Create(CreateSuspended: boolean);
  end;

type

  SendThread = class(TThread)
  private
    StatusValue:Byte;
    PrevState:LongWord;
    procedure ShowState;
  protected
    procedure Execute; override;
  public
    Constructor Create(CreateSuspended: boolean);
  end;

  CalibrationThread = class(TThread)
  private
    CalibrationState:Byte;
    NextCalibrationState:Byte;
  protected
    procedure Execute; override;
  public
    Constructor Create(CreateSuspended: boolean);
  end;

const
  USB_DEV_VID = $F000;
  USB_DEV_PID = $0005;
  INTERRUPT_OUT_EP = $04;
  INTERRUPT_IN_EP = $81;
  BULK_CHAR_OUT_EP = $02;
  BULK_CHAR_IN_EP  = $85;

  MAX_PACKET_SIZE  = 64;

  USB_RESP_TIMEOUT = 5000;

  VOLTAGE_OFF = 0;

  STR_CALIBRATION_START = 'Rozpocznij';
  STR_CALIBRATION_CANCEL = 'Anuluj';
  STR_CONNECTED = 'Połączony';
  STR_DISCONNECTED = 'Niepołączony';
  STR_DEV_NOT_FOUND = 'Urządzenie nie zostało znalezione.';
  STR_CALIBRATION_SETTING_DEFAULT_VOLTAGE = 'Ustawianie domyślnego napięcia';
  STR_CALIBRATION_AWAITING = 'Oczekiwanie na gotowość testera';
  STR_CALIBRATION_TURNING_ON = 'Załączanie HVM';
  STR_CALIBRATION_TURNING_OFF = 'Wyłączanie HVM';
  STR_CALIBRATION_PROGRAMMING = 'Programowanie';
  STR_CALIBRATION_INITIALIZE_SETTINGS = 'Inicjalizacja ustawień';
  STR_CALIBRATION_VOLTAGE_CORRECTION = 'Ustalanie korekcji napięcia';
  STR_CALIBRATION_VOLTAGE_OFFSET = 'Ustalanie offsetu napięcia';
  STR_CALIBRATION_CURRENT_CORRECTION_L = 'Ustalanie korekcji prądu - zakres L';
  STR_CALIBRATION_CURRENT_OFFSET_L_UNI = 'Ustalanie offsetu prądu - zakres L, tryb unipolarny';
  STR_CALIBRATION_CURRENT_OFFSET_L_BI = 'Ustalanie offsetu prądu - zakres L, tryb bipolarny';
  STR_CALIBRATION_CURRENT_CORRECTION_H = 'Ustalanie korekcji prądu - zakres H';
  STR_CALIBRATION_CURRENT_OFFSET_H_UNI = 'Ustalanie offsetu prądu - zakres H, tryb unipolarny';
  STR_CALIBRATION_CURRENT_OFFSET_H_BI = 'Ustalanie offsetu prądu - zakres H, tryb bipolarny';
  STR_CALIBRATION_APPLY_CORRECTION = 'Stosowanie ustawień';
  STR_CALIBRATION_VOLTAGE_VERIFY = 'Weryfikacja napięć';
  STR_CALIBRATION_CURRENT_VERIFY = 'Weryfikacja prądów';
  STR_CALIBRATION_GENERATE_REPORT = 'Generowanie raportu';
  STR_CALIBRATION_END = 'Zakończono';
  STR_CALIBRATION_ERROR = 'Niepowodzenie';
  STR_CALIBRATION_CANCELLED = 'Anulowane przez użytkownika';

  TYPE_STATUS = 0;
  TYPE_SETTINGS = 1;
  TYPE_MEAS = 2;
  TYPE_INFO = 3;
  TYPE_EVENT = 4;
  TYPE_TESTER_OUTPUTS = 5;

  STATE_PROGRAM = 0;
  STATE_SET_CURRENT = 1;
  STATE_SET_VOLTAGE = 2;
  STATE_GLASSMAN_CONNECTED = 3;
  STATE_GLASSMAN_OVERCURRENT = 4;
  STATE_HVM_REF_CONNECTED = 5;
  STATE_HVM_EXA_CONNECTED = 6;
  STATE_HVM_UPDATE_SETTINGS = 7;
  STATE_HVM_ERROR = 8;
  STATE_HVM_ALERT = 9;

  CALIBRATION_STATE_TURNING_ON = 0;
  CALIBRATION_STATE_PROGRAMMING = 1;
  CALIBRATION_STATE_INITIALIZE_SETTINGS = 2;
  CALIBRATION_STATE_VOLTAGE_CORRECTION = 3;
  CALIBRATION_STATE_VOLTAGE_OFFSET = 4;
  CALIBRATION_STATE_CURRENT_CORRECTION_L = 5;
  CALIBRATION_STATE_CURRENT_OFFSET_L_UNI = 6;
  CALIBRATION_STATE_CURRENT_OFFSET_L_BI = 7;
  CALIBRATION_STATE_CURRENT_CORRECTION_H = 8;
  CALIBRATION_STATE_CURRENT_OFFSET_H_UNI = 9;
  CALIBRATION_STATE_CURRENT_OFFSET_H_BI = 10;
  CALIBRATION_STATE_APPLY_CORRECTION = 11;
  CALIBRATION_STATE_VOLTAGE_VERIFY = 12;
  CALIBRATION_STATE_CURRENT_VERIFY = 13;
  CALIBRATION_STATE_GENERATE_REPORT = 14;

  VOLTAGE_CORR_COEF = 0.775;{dla skoku o 500V}
  VOLTAGE_OFFSET_COEF = 0.125;
  CURRENT_CORR_H_COEF = -0.08;{dla skoku 20mV; 1500/60 -> 500A; 1500/100 -> 300A}
  CURRENT_OFFSET_H_UNI_COEF = -0.2;{0-3000A; 0-120mV dla bocznika 1500/60} {0-1800A; 0-120mV dla bocznika 1500/100}
  CURRENT_OFFSET_H_BI_COEF = 0.2;{+-1500A; +-60mV dla bocznika 1500/60} {+-900A; 0-120mV dla bocznika 1500/100}
  CURRENT_CORR_L_COEF = -0.016;{dla skoku 4mV; 1500/60 -> 100A; 1500/100 -> 60A}
  CURRENT_OFFSET_L_UNI_COEF = -0.04;{0-600A; 0-24mV dla bocznika 1500/60} {0-360A; 0-24mV dla bocznika 1500/100}
  CURRENT_OFFSET_L_BI_COEF = 0.04;{+-300A; +-12mV dla bocznika 1500/60} {+-180A; +-12mV dla bocznika 1500/100}
  CORR_MAX = 10;
  CORR_MIN = -10;
  OFFSET_MAX = 30;
  OFFSET_MIN = -30;

  CR = #13;
  LF = #10;
  TAB = #9;
  CRLF = CR + LF;

var
  Form1: TForm1;
  INI:TINIFile;
  dev_handle: Pusb_dev_handle;
  dataout: Array[0..MAX_PACKET_SIZE] of Char;
  TesterState:TTesterState;
var
  RecvThreadHandle: RecvThread;
  SendThreadHandle: SendThread;
  CalibrationThreadHandle: CalibrationThread;
  intPkts:Integer = 0;
var
  usb_connected:Boolean = False;
  data_initialize:Boolean = True;
  calibration_running:Boolean = False;
  calibration_cancelled:Boolean = False;
var
  VOLTAGES:Array of Integer;
  CURRENTS_L_UNI:Array of Integer;
  CURRENTS_L_BI:Array of Integer;
  CURRENTS_H_UNI:Array of Integer;
  CURRENTS_H_BI:Array of Integer;
  CURRENTS_L_UNI_KOR:Array of Integer;
  CURRENTS_L_BI_KOR:Array of Integer;
  CURRENTS_H_UNI_KOR:Array of Integer;
  CURRENTS_H_BI_KOR:Array of Integer;
  CURRENTS_VERIFY:Array of Integer;
  CURRENTS_VERIFY_KOR:Array of Integer;
  DEFAULT_VOLTAGE: Word;
  MOD_NUMBER:Word;
  SHUNT_CURRENT:Word;
  SHUNT_VOLTAGE:Byte;
  HARD_VER:Byte;
  ZERO_I:Byte;
  INTERVAL:Byte;
  PROD_DATE: LongWord;

  PROGRAM_FLASH:Byte;
  CALIB_VOLTAGE:Byte;
  CALIB_CURRENT:Byte;
  VERIFY:Byte;
  GENERATE_REPORT:Byte;

procedure SendTesterState(StatusValue:Byte);
procedure SetTesterState(StatusBit:Byte; State:Integer);
function AwaitTesterState(StatusBit:Byte; State,timeout:Integer):Boolean;
procedure RequestTesterState(StatusValue:Byte);
procedure RefreshTesterState;
function TestStatusBit(Bit:Byte):Boolean;

implementation

{$R *.lfm}

uses
  LCLIntf, LCLType;

{ TForm1 }

constructor RecvThread.Create(CreateSuspended: boolean);
begin
   FreeOnTerminate := True;
   inherited Create(CreateSuspended);
end;

procedure RecvThread.WriteConsole;
begin
  Repeat
    end_index := Pos(LF, newLine);
    if(end_index > 0) Then begin
      newString := Copy(newLine, 0, end_index-1);
    end Else begin
      Form1.CmdBox.Write(newLine);
      Break;
    end;
      Form1.CmdBox.WriteLn(newString);
      newLine := newLine+end_index;
  until (end_index = 0);
end;

procedure RecvThread.Execute;
var
  rcvLen:Integer;
  receive_data: Array[0..MAX_PACKET_SIZE] of Char;
begin
  while (not Terminated) do begin
    receive_data := '';
    rcvLen := libusb.usb_bulk_read(dev_handle, BULK_CHAR_IN_EP, receive_data, MAX_PACKET_SIZE,-1);
    if(rcvLen > 0) Then Begin
      newLine := receive_data;
      Synchronize(@WriteConsole);
    end;
  end;
end;

constructor SendThread.Create(CreateSuspended: boolean);
begin
   FreeOnTerminate := True;
   PrevState := 0;
   inherited Create(CreateSuspended);
end;

procedure SendThread.ShowState;
begin
  Inc(intPkts);
  if (StatusValue = TYPE_STATUS) Then Begin
     if PrevState <> TesterState.Status.State Then Begin
       PrevState := TesterState.Status.State;
     end;

       Form1.UCVccLabel.Caption := Format('%d,%.3d',[Trunc(TesterState.Status.AnalogInputs.UCVcc/1000), Abs(TesterState.Status.AnalogInputs.UCVcc mod 1000)])+' V'; ;
       Form1.VccLabel.Caption := Format('%d,%.3d',[Trunc(TesterState.Status.AnalogInputs.Vcc/1000), Abs(TesterState.Status.AnalogInputs.Vcc mod 1000)])+' V'; ;
       Form1.FreqLabel.Caption := Format('%d,%.3d',[Trunc(TesterState.Status.Freq/1000), Abs(TesterState.Status.Freq mod 1000)])+' kHz';
     if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
       Form1.VoltageLabel.Caption := Format('%d,%.1d',[Trunc(TesterState.Status.Voltage/100), Trunc(Abs(TesterState.Status.Voltage mod 100)/10)])+' V';
       if TesterState.Status.Current < 0 then begin
         Form1.CurrentLabel.Caption := Format('-%d,%.2d',[Trunc(Abs(TesterState.Status.Current/100)), Abs(TesterState.Status.Current mod 100)])+' A';
       end else begin
         Form1.CurrentLabel.Caption := Format('%d,%.2d',[Trunc(Abs(TesterState.Status.Current/100)), Abs(TesterState.Status.Current mod 100)])+' A';
       end;
     end
     Else begin
       Form1.VoltageLabel.Caption := '-';
       Form1.CurrentLabel.Caption := '-';
     end;
     if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
       Form1.VoltageRefLabel.Caption := Format('%d,%.1d',[Trunc(TesterState.Status.VoltageRef/100), Trunc(Abs(TesterState.Status.VoltageRef mod 100)/10)])+' V';                     ;
       if TesterState.Status.CurrentRef < 0 then begin
         Form1.CurrentRefLabel.Caption := Format('-%d,%.2d',[Trunc(Abs(TesterState.Status.CurrentRef/100)), Abs(TesterState.Status.CurrentRef mod 100)])+' A';
       end else begin
         Form1.CurrentRefLabel.Caption := Format('%d,%.2d',[Trunc(Abs(TesterState.Status.CurrentRef/100)), Abs(TesterState.Status.CurrentRef mod 100)])+' A';
       end;
     end
     Else begin
       Form1.VoltageRefLabel.Caption := '-';
       Form1.CurrentRefLabel.Caption := '-';
     end;
     if TestStatusBit(STATE_GLASSMAN_CONNECTED) Then begin
       if(Form1.GlassSetBtn.Enabled = False) Then
         Form1.GlassSetBtn.Enabled := True;
       Form1.VoltageGlass.Caption := Format('%d,%.2d',[Trunc(TesterState.Status.VoltageGlass/100), Abs(TesterState.Status.VoltageGlass mod 100)])+' kV';
       Form1.CurrentGlass.Caption := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), Abs(TesterState.Status.CurrentGlass mod 100)])+' mA';
     end
     Else begin
       Form1.VoltageGlass.Caption := '-';
       Form1.CurrentGlass.Caption := '-';
       if(Form1.GlassSetBtn.Enabled = True) Then
         Form1.GlassSetBtn.Enabled := False;
     end;
  end
  //settings
  Else if (StatusValue = TYPE_SETTINGS) Then Begin
    Form1.StringGrid1.Cells[1,1] := IntToStr(TesterState.HvmSettings.NrModHVM);
    Form1.StringGrid1.Cells[1,2] := IntToStr(TesterState.HvmSettings.Rezerwa);
    Form1.StringGrid1.Cells[1,3] := IntToStr(TesterState.HvmSettings.HardVer);
    Form1.StringGrid1.Cells[1,4] := IntToStr(TesterState.HvmSettings.ZeroMaleI);
    Form1.StringGrid1.Cells[1,5] := IntToStr(TesterState.HvmSettings.KorMul_PradL);
    Form1.StringGrid1.Cells[1,6] := IntToStr(TesterState.HvmSettings.TypBocz_Prad);
    Form1.StringGrid1.Cells[1,7] := IntToStr(TesterState.HvmSettings.TypBocz_Nap);
    Form1.StringGrid1.Cells[1,8] := IntToStr(TesterState.HvmSettings.Interwal);
    Form1.StringGrid1.Cells[1,9] := IntToStr(TesterState.HvmSettings.Offset_Pom_Nap);
    Form1.StringGrid1.Cells[1,10] := IntToStr(TesterState.HvmSettings.Offset_Pom_PradL_Bi);
    Form1.StringGrid1.Cells[1,11] := IntToStr(TesterState.HvmSettings.Offset_Pom_PradL_Uni);
    Form1.StringGrid1.Cells[1,12] := IntToStr(TesterState.HvmSettings.Offset_Pom_PradH_Bi);
    Form1.StringGrid1.Cells[1,13] := IntToStr(TesterState.HvmSettings.Offset_Pom_PradH_Uni);
    Form1.StringGrid1.Cells[1,14] := IntToStr(TesterState.HvmSettings.KorMul_Pom_Nap);
    Form1.StringGrid1.Cells[1,15] := IntToStr(TesterState.HvmSettings.KorMul_PradH);
    Form1.StringGrid1.Cells[1,16] := IntToStr(TesterState.HvmSettings.Hvm_DataKalibr);
    Form1.StringGrid1.Cells[1,17] := IntToStr(TesterState.HvmSettings.Hvm_DataProd);
    Form1.StringGrid1.Cells[1,18] := IntToStr(TesterState.HvmSettings.EE_CrcKalibr);
  end;
  {Else if (StatusValue = TYPE_MEAS) Then begin
  //meas
    Form1.StringGrid1.Cells[3,1] := IntToStr(TesterState.HvmMeas.voltage);
    Form1.StringGrid1.Cells[3,2] := IntToStr(TesterState.HvmMeas.voltage_r);
    Form1.StringGrid1.Cells[3,3] := IntToStr(TesterState.HvmMeas.current);
    Form1.StringGrid1.Cells[3,4] := IntToStr(TesterState.HvmMeas.current_r);
    Form1.StringGrid1.Cells[3,5] := IntToStr(TesterState.HvmMeas.energyIn);
    Form1.StringGrid1.Cells[3,6] := IntToStr(TesterState.HvmMeas.energyIn_r);
    Form1.StringGrid1.Cells[3,7] := IntToStr(TesterState.HvmMeas.energyOut);
    Form1.StringGrid1.Cells[3,8] := IntToStr(TesterState.HvmMeas.energyOut_r);
    Form1.StringGrid1.Cells[3,9] := IntToStr(TesterState.HvmMeas.time);
    Form1.StringGrid1.Cells[3,10] := IntToStr(TesterState.HvmMeas.eventIndex);
    Form1.StringGrid1.Cells[3,11] := IntToStr(TesterState.HvmMeas.errStat);
    Form1.StringGrid1.Cells[3,12] := IntToStr(TesterState.HvmMeas.energyAvg);
    Form1.StringGrid1.Cells[3,13] := IntToStr(TesterState.HvmMeas.energyAvg_r);
  end
  Else if (StatusValue = TYPE_INFO) Then begin
  //info
    Form1.StringGrid1.Cells[5,1] := IntToStr(TesterState.HvmInfo.HardVer);
    Form1.StringGrid1.Cells[5,2] := IntToStr(TesterState.HvmInfo.SoftVer);
    Form1.StringGrid1.Cells[5,3] := IntToStr(TesterState.HvmInfo.RPomIU);
    Form1.StringGrid1.Cells[5,4] := IntToStr(TesterState.HvmInfo.NrHvm);
    Form1.StringGrid1.Cells[5,5] := IntToStr(TesterState.HvmInfo.DTContrMetr);
    Form1.StringGrid1.Cells[5,6] := IntToStr(TesterState.HvmInfo.TypBocz_PradL);
    Form1.StringGrid1.Cells[5,7] := IntToStr(TesterState.HvmInfo.TypBocz_PradH);
    Form1.StringGrid1.Cells[5,8] := IntToStr(TesterState.HvmInfo.TypBocz_Nap);
    Form1.StringGrid1.Cells[5,9] := IntToStr(TesterState.HvmInfo.DTProd);
    Form1.StringGrid1.Cells[5,10] := IntToStr(TesterState.HvmInfo.HvmRstStatusErr);
    Form1.StringGrid1.Cells[5,11] := IntToStr(TesterState.HvmInfo.HvmRstStatusTmp);
    Form1.StringGrid1.Cells[5,12] := IntToStr(TesterState.HvmInfo.Interval);
  end
  Else if (StatusValue = TYPE_EVENT) Then begin
  //event
    Form1.StringGrid1.Cells[7,1] := IntToStr(TesterState.HvmEvent.hvmIndex);
    Form1.StringGrid1.Cells[7,2] := IntToStr(TesterState.HvmEvent.eventType);
    Form1.StringGrid1.Cells[7,3] := IntToStr(TesterState.HvmEvent.time);
    Form1.StringGrid1.Cells[7,4] := IntToStr(TesterState.HvmEvent.energyIn);
    Form1.StringGrid1.Cells[7,5] := IntToStr(TesterState.HvmEvent.energyIn_r);
    Form1.StringGrid1.Cells[7,6] := IntToStr(TesterState.HvmEvent.energyOut);
    Form1.StringGrid1.Cells[7,7] := IntToStr(TesterState.HvmEvent.energyOut_r);
    Form1.StringGrid1.Cells[7,8] := IntToStr(TesterState.HvmEvent.eventIndex);
    Form1.StringGrid1.Cells[7,9] := IntToStr(TesterState.HvmEvent.reserve);
    Form1.StringGrid1.Cells[7,10] := IntToStr(TesterState.HvmEvent.hvmStat);
    Form1.StringGrid1.Cells[7,11] := IntToStr(TesterState.HvmEvent.pos[0]);
    Form1.StringGrid1.Cells[7,12] := IntToStr(TesterState.HvmEvent.eventCrc);
  end;  }
end;

procedure SendThread.Execute;
var
  packetSize:Integer;
  status_data: Array[0..MAX_PACKET_SIZE] of Char;
begin
  while (not Terminated) do begin
   while(usb_connected = False) do begin
     usb_connected := Form1.OpenUsb;
     Sleep(1000);
   end;

   packetSize := libusb.usb_interrupt_read(dev_handle,INTERRUPT_IN_EP, status_data, MAX_PACKET_SIZE, -1);
   if(packetSize < 0) Then  begin
     Form1.CloseUsb;
     usb_connected := False;
     data_initialize := True;
     Sleep(2000);
   end
   Else begin
      StatusValue := ord(status_data[0]);
      if(StatusValue = TYPE_STATUS) Then
      begin
        Move(status_data[1], TesterState.Status.State, packetSize-1);
        if data_initialize Then
          RequestTesterState(TYPE_SETTINGS);
      end
      Else if (StatusValue = TYPE_SETTINGS) Then
      begin
        Move(status_data[1], TesterState.HvmSettings, packetSize-1);
        if data_initialize Then begin
          RequestTesterState(TYPE_MEAS);
        end;
      end
      Else if (StatusValue = TYPE_MEAS) Then
      begin
        Move(status_data[1], TesterState.HvmMeas, packetSize-1);
        if data_initialize Then begin
          RequestTesterState(TYPE_INFO);
        end;
      end
      Else if (StatusValue = TYPE_INFO) Then
      begin
        Move(status_data[1], TesterState.HvmInfo, packetSize-1);
        if data_initialize Then begin
          RequestTesterState(TYPE_EVENT);
        end;
      end
      Else if (StatusValue = TYPE_EVENT) Then
      begin
        Move(status_data[1], TesterState.HvmEvent, packetSize-1);
        if data_initialize Then
          data_initialize := False;
      end;
      Synchronize(@ShowState);
   end;
  end;
end;

constructor CalibrationThread.Create(CreateSuspended: boolean);
begin
   FreeOnTerminate := True;
   inherited Create(CreateSuspended);
end;

procedure CalibrationThread.Execute;
var
  res:Boolean;
  i:Integer;
  Diff:Currency;
  DiffDiff:Currency;
  DiffAvg:Currency;
  DiffDiffAvg:Currency;

  YY,MM,DD : Word;

  calc_voltage_offset:ShortInt = 0;
  calc_voltage_corr:ShortInt = 0;
  calc_current_offset_h_uni:ShortInt = 0;
  calc_current_offset_h_bi:ShortInt = 0;
  calc_current_offset_l_uni:ShortInt = 0;
  calc_current_offset_l_bi:ShortInt = 0;
  calc_current_corr_h:ShortInt = 0;
  calc_current_corr_l:ShortInt = 0;

begin
  calibration_cancelled := False;
  CalibrationState := CALIBRATION_STATE_TURNING_ON;
  Form1.VoltageCorrGrid.RowCount:=1;
  Form1.VoltageOffsetGrid.RowCount:=1;
  Form1.CurrentCorrLGrid.RowCount:=1;
  Form1.CurrentOffsetLUniGrid.RowCount:=1;
  Form1.CurrentOffsetLBiGrid.RowCount:=1;
  Form1.CurrentCorrHGrid.RowCount:=1;
  Form1.CurrentOffsetHUniGrid.RowCount:=1;
  Form1.CurrentOffsetHBiGrid.RowCount:=1;
  Form1.VoltageVerifyGrid.RowCount:=1;
  Form1.CurrentVerifyGrid.RowCount:=1;

  Form1.VoltageCorrLabel.Caption:='-';
  Form1.VoltageOffsetLabel.Caption:='-';
  Form1.CurrentCorrLLabel.Caption:='-';
  Form1.CurrentOffsetLUniLabel.Caption:='-';
  Form1.CurrentOffsetLBiLabel.Caption:='-';
  Form1.CurrentCorrHLabel.Caption:='-';
  Form1.CurrentOffsetHUniLabel.Caption:='-';
  Form1.CurrentOffsetHBiLabel.Caption:='-';

  while (not Terminated) do begin
     res := False;
     if(CalibrationState = CALIBRATION_STATE_TURNING_ON) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_AWAITING;
       AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_TURNING_ON;
       TesterState.TesterOutputs.glassVoltage:=DEFAULT_VOLTAGE;
       SendTesterState(TYPE_TESTER_OUTPUTS);
       SetTesterState(STATE_SET_VOLTAGE, 1);
       Sleep(100);
       res := AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       CalibrationState := CALIBRATION_STATE_PROGRAMMING;
     end
     Else if(CalibrationState = CALIBRATION_STATE_PROGRAMMING) Then begin
       if not Form1.ProgramFlashBox.Checked then begin
         CalibrationState := CALIBRATION_STATE_INITIALIZE_SETTINGS;
       end
       Else begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_PROGRAMMING;

       SetTesterState(STATE_PROGRAM, 1);
       Sleep(100);
       if Terminated Then
         Break;
       res := AwaitTesterState(STATE_PROGRAM, 0, 30000);
       if res Then begin
         CalibrationState := CALIBRATION_STATE_INITIALIZE_SETTINGS;
         Sleep(2000);
       end
       Else begin
         Terminate;
       end;
       end;
     end

     Else if(CalibrationState = CALIBRATION_STATE_INITIALIZE_SETTINGS) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_INITIALIZE_SETTINGS;

       RefreshTesterState;
       Sleep(1000);

       if Form1.ProgramFlashBox.Checked then begin
         TesterState.HvmSettings.NrModHVM               :=      MOD_NUMBER;
         TesterState.HvmSettings.HardVer                :=      HARD_VER;
         if Form1.ZeroMaleICheckbox.Checked Then begin
            TesterState.HvmSettings.ZeroMaleI:=1;//wylaczenie wymuszenia
         end Else begin
            TesterState.HvmSettings.ZeroMaleI:=0;//wylaczenie wymuszenia
         end;
         TesterState.HvmSettings.TypBocz_Prad           :=      SHUNT_CURRENT;
         TesterState.HvmSettings.TypBocz_Nap            :=      SHUNT_VOLTAGE;
         TesterState.HvmSettings.Interwal               :=      INTERVAL;
         TesterState.HvmSettings.Hvm_DataKalibr         :=      0;
         TesterState.HvmSettings.KorMul_PradL           :=      0;
         TesterState.HvmSettings.Offset_Pom_Nap         :=      0;
         TesterState.HvmSettings.Offset_Pom_PradL_Bi    :=      0;
         TesterState.HvmSettings.Offset_Pom_PradL_Uni   :=      0;
         TesterState.HvmSettings.Offset_Pom_PradH_Bi    :=      0;
         TesterState.HvmSettings.Offset_Pom_PradH_Uni   :=      0;
         TesterState.HvmSettings.KorMul_Pom_Nap         :=      0;
         TesterState.HvmSettings.KorMul_PradH           :=      0;
         TesterState.HvmSettings.Rezerwa                :=      0;
         TesterState.HvmSettings.EE_CrcKalibr           :=      0;
         DeCodeDate (Date,YY,MM,DD);
         TesterState.HvmSettings.Hvm_DataProd:=YY*10000+MM*100+DD;
       end;

       if Form1.CalibVoltageBox.Checked then begin
         TesterState.HvmSettings.NrModHVM               :=      MOD_NUMBER;
         TesterState.HvmSettings.HardVer                :=      HARD_VER;
         TesterState.HvmSettings.Interwal               :=      INTERVAL;
         TesterState.HvmSettings.Hvm_DataKalibr         :=      0;
         TesterState.HvmSettings.Offset_Pom_Nap         :=      0;
         TesterState.HvmSettings.KorMul_Pom_Nap         :=      0;
         TesterState.HvmSettings.Rezerwa                :=      0;
         TesterState.HvmSettings.EE_CrcKalibr           :=      0;
       end;

       if Form1.CalibCurrentBox.Checked then begin
         TesterState.HvmSettings.NrModHVM               :=      MOD_NUMBER;
         TesterState.HvmSettings.HardVer                :=      HARD_VER;
         TesterState.HvmSettings.ZeroMaleI              :=      0;
         TesterState.HvmSettings.TypBocz_Prad           :=      SHUNT_CURRENT;
         TesterState.HvmSettings.TypBocz_Nap            :=      SHUNT_VOLTAGE;
         TesterState.HvmSettings.Interwal               :=      INTERVAL;
         TesterState.HvmSettings.Hvm_DataKalibr         :=      0;
         TesterState.HvmSettings.KorMul_PradL           :=      0;
         TesterState.HvmSettings.Offset_Pom_PradL_Bi    :=      0;
         TesterState.HvmSettings.Offset_Pom_PradL_Uni   :=      0;
         TesterState.HvmSettings.Offset_Pom_PradH_Bi    :=      0;
         TesterState.HvmSettings.Offset_Pom_PradH_Uni   :=      0;
         TesterState.HvmSettings.KorMul_PradH           :=      0;
         TesterState.HvmSettings.Rezerwa                :=      0;
         TesterState.HvmSettings.EE_CrcKalibr           :=      0;
       end;

       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 2000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(1000);
       CalibrationState := CALIBRATION_STATE_VOLTAGE_CORRECTION;
     end
     Else if(CalibrationState = CALIBRATION_STATE_VOLTAGE_CORRECTION) Then begin
       if not Form1.CalibVoltageBox.Checked then begin
         CalibrationState := CALIBRATION_STATE_CURRENT_CORRECTION_L;
       end Else begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_VOLTAGE_CORRECTION;
       DiffAvg := 0;
       DiffDiffAvg := 0;
       for i:=0 to Length(VOLTAGES)-1 Do Begin
         TesterState.TesterOutputs.glassVoltage:=VOLTAGES[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_VOLTAGE, 1);
         Sleep(100);
         if Terminated Then
           Break;
         res := AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.VoltageCorrGrid.RowCount:=Form1.VoltageCorrGrid.RowCount+1;
         Form1.VoltageCorrGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.VoltageCorrGrid.Cells[1, i+1] := IntToStr(VOLTAGES[i]*10);
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.VoltageCorrGrid.Cells[2, i+1] := Format('%d,%.1d',[Trunc(TesterState.Status.Voltage/100), Trunc(Abs(TesterState.Status.Voltage mod 100)/10)]);
         end Else begin
           Form1.VoltageCorrGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.VoltageCorrGrid.Cells[3, i+1] := Format('%d,%.1d',[Trunc(TesterState.Status.VoltageRef/100), Trunc(Abs(TesterState.Status.VoltageRef mod 100)/10)]);
         end Else begin
           Form1.VoltageCorrGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.VoltageRef-TesterState.Status.Voltage)/100;
           Form1.VoltageCorrGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.VoltageCorrGrid.Cells[4, i+1] := '-';
         end;
          if i>0 Then begin
            DiffDiff := Diff-StrToFloatDef(Form1.VoltageCorrGrid.Cells[4, i],0);
            Form1.VoltageCorrGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
          end Else begin
            Form1.VoltageCorrGrid.Cells[5, i+1] := '-';
          end;
         Form1.VoltageCorrGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
         DiffAvg := DiffAvg+Diff/Length(VOLTAGES);
         if i>0 Then
           DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(VOLTAGES)-1);
       end;
       If not Terminated Then begin
       calc_voltage_corr := Round(DiffDiffAvg/VOLTAGE_CORR_COEF);
       Form1.VoltageCorrGrid.RowCount:=Form1.VoltageCorrGrid.RowCount+1;
       Form1.VoltageCorrGrid.Cells[4, Length(VOLTAGES)+1] := FloatToStr(DiffAvg);
       Form1.VoltageCorrGrid.Cells[5, Length(VOLTAGES)+1] := FloatToStr(DiffDiffAvg);
       Form1.VoltageCorrLabel.Caption := FloatToStr(DiffDiffAvg)+'/'+FloatToStr(VOLTAGE_CORR_COEF) +'='+FloatToStr(DiffDiffAvg/VOLTAGE_CORR_COEF)+'='+IntToStr(calc_voltage_corr);
       if (calc_voltage_corr < CORR_MIN) or ((calc_voltage_corr > CORR_MAX)) Then begin
         res := False;
         Terminate;
         Break;
       end;
       CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
       NextCalibrationState := CALIBRATION_STATE_VOLTAGE_OFFSET;
       end;
       end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_VOLTAGE_OFFSET) Then begin
       if not Form1.CalibVoltageBox.Checked then begin
         CalibrationState := CALIBRATION_STATE_CURRENT_CORRECTION_L;
       end Else begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_VOLTAGE_OFFSET;
       DiffAvg := 0;
       DiffDiffAvg := 0;
       for i:=0 to Length(VOLTAGES)-1 Do Begin
         TesterState.TesterOutputs.glassVoltage:=VOLTAGES[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_VOLTAGE, 1);
         Sleep(100);
         if Terminated Then
           Break;
         res := AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.VoltageOffsetGrid.RowCount:=Form1.VoltageOffsetGrid.RowCount+1;
         Form1.VoltageOffsetGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.VoltageOffsetGrid.Cells[1, i+1] := IntToStr(VOLTAGES[i]*10);
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.VoltageOffsetGrid.Cells[2, i+1] := Format('%d,%.1d',[Trunc(TesterState.Status.Voltage/100), Trunc(Abs(TesterState.Status.Voltage mod 100)/10)]);
         end Else begin
           Form1.VoltageOffsetGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.VoltageOffsetGrid.Cells[3, i+1] := Format('%d,%.1d',[Trunc(TesterState.Status.VoltageRef/100), Trunc(Abs(TesterState.Status.VoltageRef mod 100)/10)]);
         end Else begin
           Form1.VoltageOffsetGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.VoltageRef-TesterState.Status.Voltage)/100;
           Form1.VoltageOffsetGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.VoltageOffsetGrid.Cells[4, i+1] := '-';
         end;
          if i>0 Then begin
            DiffDiff := Diff-StrToFloatDef(Form1.VoltageOffsetGrid.Cells[4, i],0);
            Form1.VoltageOffsetGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
          end Else begin
            Form1.VoltageOffsetGrid.Cells[5, i+1] := '-';
          end;
         Form1.VoltageOffsetGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
         DiffAvg := DiffAvg+Diff/Length(VOLTAGES);
         if i>0 Then
           DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(VOLTAGES)-1);
       end;
       If not Terminated Then begin
       calc_voltage_offset := Round(DiffAvg/VOLTAGE_OFFSET_COEF);
       Form1.VoltageOffsetGrid.RowCount:=Form1.VoltageOffsetGrid.RowCount+1;
       Form1.VoltageOffsetGrid.Cells[4, Length(VOLTAGES)+1] := FloatToStr(DiffAvg);
       Form1.VoltageOffsetGrid.Cells[5, Length(VOLTAGES)+1] := FloatToStr(DiffDiffAvg);
       Form1.VoltageOffsetLabel.Caption := FloatToStr(DiffAvg)+'/'+FloatToStr(VOLTAGE_OFFSET_COEF) +'='+FloatToStr(DiffAvg/VOLTAGE_OFFSET_COEF)+'='+IntToStr(calc_voltage_offset);
       if (calc_voltage_offset < OFFSET_MIN) or ((calc_voltage_offset > OFFSET_MAX)) Then begin
         res := False;
         Terminate;
         Break;
       end;
       CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
       NextCalibrationState := CALIBRATION_STATE_CURRENT_CORRECTION_L;
       end;
       end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_CURRENT_CORRECTION_L) Then begin
       if not Form1.CalibCurrentBox.Checked then begin
         CalibrationState := CALIBRATION_STATE_VOLTAGE_VERIFY;
       end Else begin

       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_SETTING_DEFAULT_VOLTAGE;
       TesterState.TesterOutputs.glassVoltage:=DEFAULT_VOLTAGE;
       SendTesterState(TYPE_TESTER_OUTPUTS);
       SetTesterState(STATE_SET_VOLTAGE, 1);
       Sleep(100);
       res := AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
       if res <> True Then begin
         Terminate;
         Break;
       end;

       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CURRENT_CORRECTION_L;
       DiffAvg := 0;
       DiffDiffAvg := 0;

       TesterState.HvmSettings.ZeroMaleI:=6;//wymuszenie zakres L uni
       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 2000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(2000);

       for i:=0 to Length(CURRENTS_L_UNI)-1 Do Begin
         TesterState.TesterOutputs.currentA:=CURRENTS_L_UNI_KOR[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_CURRENT, 1);
         Sleep(100);
         if not Terminated Then
           res := AwaitTesterState(STATE_SET_CURRENT, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.CurrentCorrLGrid.RowCount:=Form1.CurrentCorrLGrid.RowCount+1;
         Form1.CurrentCorrLGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.CurrentCorrLGrid.Cells[1, i+1] := IntToStr(Round(CURRENTS_L_UNI[i]));
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.CurrentCorrLGrid.Cells[2, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.Current/100), Abs(TesterState.Status.Current mod 100)]);
         end Else begin
           Form1.CurrentCorrLGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.CurrentCorrLGrid.Cells[3, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentRef/100), Abs(TesterState.Status.CurrentRef mod 100)]);

         end Else begin
           Form1.CurrentCorrLGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.CurrentRef-TesterState.Status.Current)/100;
           Form1.CurrentCorrLGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.CurrentCorrLGrid.Cells[4, i+1] := '-';
         end;
           if i>0 Then begin
              DiffDiff := Diff-StrToFloatDef(Form1.CurrentCorrLGrid.Cells[4, i],0);
              Form1.CurrentCorrLGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
           end Else begin
               Form1.CurrentCorrLGrid.Cells[5, i+1] := '-';
           end;
           Form1.CurrentCorrLGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
           DiffAvg := DiffAvg+Diff/Length(CURRENTS_L_UNI);
           if i>0 Then
              DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(CURRENTS_L_UNI)-1);
         end;
       If not Terminated Then begin
       calc_current_corr_l := Round(DiffDiffAvg/CURRENT_CORR_L_COEF);
       Form1.CurrentCorrLGrid.RowCount:=Form1.CurrentCorrLGrid.RowCount+1;
       Form1.CurrentCorrLGrid.Cells[4, Length(CURRENTS_L_UNI)+1] := FloatToStr(DiffAvg);
       Form1.CurrentCorrLGrid.Cells[5, Length(CURRENTS_L_UNI)+1] := FloatToStr(DiffDiffAvg);
       Form1.CurrentCorrLLabel.Caption := FloatToStr(DiffDiffAvg)+'/'+FloatToStr(CURRENT_CORR_L_COEF) +'='+FloatToStr(DiffDiffAvg/CURRENT_CORR_L_COEF)+'='+IntToStr(calc_current_corr_l);
       CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
       NextCalibrationState := CALIBRATION_STATE_CURRENT_OFFSET_L_UNI;
       end;
       end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_CURRENT_OFFSET_L_UNI) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CURRENT_OFFSET_L_UNI;
       DiffAvg := 0;
       DiffDiffAvg := 0;
        for i:=0 to Length(CURRENTS_L_UNI)-1 Do Begin
         TesterState.TesterOutputs.currentA:=CURRENTS_L_UNI_KOR[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_CURRENT, 1);
         Sleep(100);
         if not Terminated Then
           res := AwaitTesterState(STATE_SET_CURRENT, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.CurrentOffsetLUniGrid.RowCount:=Form1.CurrentOffsetLUniGrid.RowCount+1;
         Form1.CurrentOffsetLUniGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.CurrentOffsetLUniGrid.Cells[1, i+1] := IntToStr(Round(CURRENTS_L_UNI[i]));
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.CurrentOffsetLUniGrid.Cells[2, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.Current/100), Abs(TesterState.Status.Current mod 100)]);
         end Else begin
           Form1.CurrentOffsetLUniGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.CurrentOffsetLUniGrid.Cells[3, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentRef/100), Abs(TesterState.Status.CurrentRef mod 100)]);

         end Else begin
           Form1.CurrentOffsetLUniGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.CurrentRef-TesterState.Status.Current)/100;
           Form1.CurrentOffsetLUniGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.CurrentOffsetLUniGrid.Cells[4, i+1] := '-';
         end;
           if i>0 Then begin
              DiffDiff := Diff-StrToFloatDef(Form1.CurrentOffsetLUniGrid.Cells[4, i],0);
              Form1.CurrentOffsetLUniGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
           end Else begin
               Form1.CurrentOffsetLUniGrid.Cells[5, i+1] := '-';
           end;
           Form1.CurrentOffsetLUniGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
           DiffAvg := DiffAvg+Diff/Length(CURRENTS_L_UNI);
           if i>0 Then
              DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(CURRENTS_L_UNI)-1);
         end;
        if not Terminated Then begin
           calc_current_offset_l_uni := Round(DiffAvg/CURRENT_OFFSET_L_UNI_COEF);
           Form1.CurrentOffsetLUniGrid.RowCount:=Form1.CurrentOffsetLUniGrid.RowCount+1;
           Form1.CurrentOffsetLUniGrid.Cells[4, Length(CURRENTS_L_UNI)+1] := FloatToStr(DiffAvg);
           Form1.CurrentOffsetLUniGrid.Cells[5, Length(CURRENTS_L_UNI)+1] := FloatToStr(DiffDiffAvg);
           Form1.CurrentOffsetLUniLabel.Caption := FloatToStr(DiffAvg)+'/'+FloatToStr(CURRENT_OFFSET_L_UNI_COEF) +'='+FloatToStr(DiffAvg/CURRENT_OFFSET_L_UNI_COEF)+'='+IntToStr(calc_current_offset_l_uni);
           CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
           NextCalibrationState := CALIBRATION_STATE_CURRENT_OFFSET_L_BI;
        end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_CURRENT_OFFSET_L_BI) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CURRENT_OFFSET_L_BI;
       DiffAvg := 0;
       DiffDiffAvg := 0;

       TesterState.HvmSettings.ZeroMaleI:=2;//wymuszenie zakres L bi
       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 2000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(2000);

        for i:=0 to Length(CURRENTS_L_BI)-1 Do Begin
         TesterState.TesterOutputs.currentA:=CURRENTS_L_BI_KOR[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_CURRENT, 1);
         Sleep(100);
         if not Terminated Then
           res := AwaitTesterState(STATE_SET_CURRENT, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.CurrentOffsetLBiGrid.RowCount:=Form1.CurrentOffsetLBiGrid.RowCount+1;
         Form1.CurrentOffsetLBiGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.CurrentOffsetLBiGrid.Cells[1, i+1] := IntToStr(Round(CURRENTS_L_BI[i]));
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.CurrentOffsetLBiGrid.Cells[2, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.Current/100), Abs(TesterState.Status.Current mod 100)]);
         end Else begin
           Form1.CurrentOffsetLBiGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.CurrentOffsetLBiGrid.Cells[3, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentRef/100), Abs(TesterState.Status.CurrentRef mod 100)]);

         end Else begin
           Form1.CurrentOffsetLBiGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.CurrentRef-TesterState.Status.Current)/100;
           Form1.CurrentOffsetLBiGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.CurrentOffsetLBiGrid.Cells[4, i+1] := '-';
         end;
           if i>0 Then begin
              DiffDiff := Diff-StrToFloatDef(Form1.CurrentOffsetLBiGrid.Cells[4, i],0);
              Form1.CurrentOffsetLBiGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
           end Else begin
               Form1.CurrentOffsetLBiGrid.Cells[5, i+1] := '-';
           end;
           Form1.CurrentOffsetLBiGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
           DiffAvg := DiffAvg+Diff/Length(CURRENTS_L_BI);
           if i>0 Then
              DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(CURRENTS_L_BI)-1);
         end;
        if not Terminated Then begin
           calc_current_offset_l_bi := Round(DiffAvg/CURRENT_OFFSET_L_BI_COEF);
           Form1.CurrentOffsetLBiGrid.RowCount:=Form1.CurrentOffsetLBiGrid.RowCount+1;
           Form1.CurrentOffsetLBiGrid.Cells[4, Length(CURRENTS_L_BI)+1] := FloatToStr(DiffAvg);
           Form1.CurrentOffsetLBiGrid.Cells[5, Length(CURRENTS_L_BI)+1] := FloatToStr(DiffDiffAvg);
           Form1.CurrentOffsetLBiLabel.Caption := FloatToStr(DiffAvg)+'/'+FloatToStr(CURRENT_OFFSET_L_BI_COEF) +'='+FloatToStr(DiffAvg/CURRENT_OFFSET_L_BI_COEF)+'='+IntToStr(calc_current_offset_l_bi);
           CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
           NextCalibrationState := CALIBRATION_STATE_CURRENT_CORRECTION_H;
        end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_CURRENT_CORRECTION_H) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CURRENT_CORRECTION_H;
       DiffAvg := 0;
       DiffDiffAvg := 0;

       TesterState.HvmSettings.ZeroMaleI:=14;//wymuszenie zakres H uni
       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 2000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(2000);

        for i:=0 to Length(CURRENTS_H_UNI)-1 Do Begin
         TesterState.TesterOutputs.currentA:=CURRENTS_H_UNI_KOR[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_CURRENT, 1);
         Sleep(100);
         if not Terminated Then
           res := AwaitTesterState(STATE_SET_CURRENT, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.CurrentCorrHGrid.RowCount:=Form1.CurrentCorrHGrid.RowCount+1;
         Form1.CurrentCorrHGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.CurrentCorrHGrid.Cells[1, i+1] := IntToStr(Round(CURRENTS_H_UNI[i]));
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.CurrentCorrHGrid.Cells[2, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.Current/100), Abs(TesterState.Status.Current mod 100)]);
         end Else begin
           Form1.CurrentCorrHGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.CurrentCorrHGrid.Cells[3, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentRef/100), Abs(TesterState.Status.CurrentRef mod 100)]);

         end Else begin
           Form1.CurrentCorrHGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.CurrentRef-TesterState.Status.Current)/100;
           Form1.CurrentCorrHGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.CurrentCorrHGrid.Cells[4, i+1] := '-';
         end;
           if i>0 Then begin
              DiffDiff := Diff-StrToFloatDef(Form1.CurrentCorrHGrid.Cells[4, i],0);
              Form1.CurrentCorrHGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
           end Else begin
               Form1.CurrentCorrHGrid.Cells[5, i+1] := '-';
           end;
           Form1.CurrentCorrHGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
           DiffAvg := DiffAvg+Diff/Length(CURRENTS_H_UNI);
           if i>0 Then
              DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(CURRENTS_H_UNI)-1);
         end;
        if not Terminated then begin
           calc_current_corr_h := Round(DiffDiffAvg/CURRENT_CORR_H_COEF);
           Form1.CurrentCorrHGrid.RowCount:=Form1.CurrentCorrHGrid.RowCount+1;
           Form1.CurrentCorrHGrid.Cells[4, Length(CURRENTS_H_UNI)+1] := FloatToStr(DiffAvg);
           Form1.CurrentCorrHGrid.Cells[5, Length(CURRENTS_H_UNI)+1] := FloatToStr(DiffDiffAvg);
           Form1.CurrentCorrHLabel.Caption := FloatToStr(DiffDiffAvg)+'/'+FloatToStr(CURRENT_CORR_H_COEF) +'='+FloatToStr(DiffDiffAvg/CURRENT_CORR_H_COEF)+'='+IntToStr(calc_current_corr_h);
           CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
           NextCalibrationState := CALIBRATION_STATE_CURRENT_OFFSET_H_UNI;
        end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_CURRENT_OFFSET_H_UNI) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CURRENT_OFFSET_H_UNI;
       DiffAvg := 0;
       DiffDiffAvg := 0;

        for i:=0 to Length(CURRENTS_H_UNI)-1 Do Begin
         TesterState.TesterOutputs.currentA:=CURRENTS_H_UNI_KOR[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_CURRENT, 1);
         Sleep(100);
         if not Terminated Then
           res := AwaitTesterState(STATE_SET_CURRENT, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.CurrentOffsetHUniGrid.RowCount:=Form1.CurrentOffsetHUniGrid.RowCount+1;
         Form1.CurrentOffsetHUniGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.CurrentOffsetHUniGrid.Cells[1, i+1] := IntToStr(Round(CURRENTS_H_UNI[i]));
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.CurrentOffsetHUniGrid.Cells[2, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.Current/100), Abs(TesterState.Status.Current mod 100)]);
         end Else begin
           Form1.CurrentOffsetHUniGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.CurrentOffsetHUniGrid.Cells[3, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentRef/100), Abs(TesterState.Status.CurrentRef mod 100)]);

         end Else begin
           Form1.CurrentOffsetHUniGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.CurrentRef-TesterState.Status.Current)/100;
           Form1.CurrentOffsetHUniGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.CurrentOffsetHUniGrid.Cells[4, i+1] := '-';
         end;
           if i>0 Then begin
              DiffDiff := Diff-StrToFloatDef(Form1.CurrentOffsetHUniGrid.Cells[4, i],0);
              Form1.CurrentOffsetHUniGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
           end Else begin
               Form1.CurrentOffsetHUniGrid.Cells[5, i+1] := '-';
           end;
           Form1.CurrentOffsetHUniGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
           DiffAvg := DiffAvg+Diff/Length(CURRENTS_H_UNI);
           if i>0 Then
              DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(CURRENTS_H_UNI)-1);
         end;
        if not Terminated Then begin
           calc_current_offset_h_uni := Round(DiffAvg/CURRENT_OFFSET_H_UNI_COEF);
           Form1.CurrentOffsetHUniGrid.RowCount:=Form1.CurrentOffsetHUniGrid.RowCount+1;
           Form1.CurrentOffsetHUniGrid.Cells[4, Length(CURRENTS_H_UNI)+1] := FloatToStr(DiffAvg);
           Form1.CurrentOffsetHUniGrid.Cells[5, Length(CURRENTS_H_UNI)+1] := FloatToStr(DiffDiffAvg);
           Form1.CurrentOffsetHUniLabel.Caption := FloatToStr(DiffAvg)+'/'+FloatToStr(CURRENT_OFFSET_H_UNI_COEF) +'='+FloatToStr(DiffAvg/CURRENT_OFFSET_H_UNI_COEF)+'='+IntToStr(calc_current_offset_h_uni);
           CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
           NextCalibrationState := CALIBRATION_STATE_CURRENT_OFFSET_H_BI;
        end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_CURRENT_OFFSET_H_BI) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CURRENT_OFFSET_H_BI;
       DiffAvg := 0;
       DiffDiffAvg := 0;

       TesterState.HvmSettings.ZeroMaleI:=10;//wymuszenie zakres H bi
       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 2000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(2000);
          //coment
        for i:=0 to Length(CURRENTS_H_BI)-1 Do Begin
         TesterState.TesterOutputs.currentA:=CURRENTS_H_BI_KOR[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_CURRENT, 1);
         Sleep(100);
         if not Terminated Then
           res := AwaitTesterState(STATE_SET_CURRENT, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.CurrentOffsetHBiGrid.RowCount:=Form1.CurrentOffsetHBiGrid.RowCount+1;
         Form1.CurrentOffsetHBiGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.CurrentOffsetHBiGrid.Cells[1, i+1] := IntToStr(Round(CURRENTS_H_BI[i]));
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.CurrentOffsetHBiGrid.Cells[2, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.Current/100), Abs(TesterState.Status.Current mod 100)]);
         end Else begin
           Form1.CurrentOffsetHBiGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.CurrentOffsetHBiGrid.Cells[3, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentRef/100), Abs(TesterState.Status.CurrentRef mod 100)]);

         end Else begin
           Form1.CurrentOffsetHBiGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.CurrentRef-TesterState.Status.Current)/100;
           Form1.CurrentOffsetHBiGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.CurrentOffsetHBiGrid.Cells[4, i+1] := '-';
         end;
           if i>0 Then begin
              DiffDiff := Diff-StrToFloatDef(Form1.CurrentOffsetHBiGrid.Cells[4, i],0);
              Form1.CurrentOffsetHBiGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
           end Else begin
               Form1.CurrentOffsetHBiGrid.Cells[5, i+1] := '-';
           end;
           Form1.CurrentOffsetHBiGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
           DiffAvg := DiffAvg+Diff/Length(CURRENTS_H_BI);
           if i>0 Then
              DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(CURRENTS_H_BI)-1);
         end;
        if not Terminated Then begin
           calc_current_offset_h_bi := Round(DiffAvg/CURRENT_OFFSET_H_BI_COEF);
           Form1.CurrentOffsetHBiGrid.RowCount:=Form1.CurrentOffsetHBiGrid.RowCount+1;
           Form1.CurrentOffsetHBiGrid.Cells[4, Length(CURRENTS_H_BI)+1] := FloatToStr(DiffAvg);
           Form1.CurrentOffsetHBiGrid.Cells[5, Length(CURRENTS_H_BI)+1] := FloatToStr(DiffDiffAvg);
           Form1.CurrentOffsetHBiLabel.Caption := FloatToStr(DiffAvg)+'/'+FloatToStr(CURRENT_OFFSET_H_BI_COEF) +'='+FloatToStr(DiffAvg/CURRENT_OFFSET_H_BI_COEF)+'='+IntToStr(calc_current_offset_h_bi);
           CalibrationState := CALIBRATION_STATE_APPLY_CORRECTION;
           NextCalibrationState := CALIBRATION_STATE_VOLTAGE_VERIFY;
        end;

       if Form1.ZeroMaleICheckbox.Checked Then begin
         TesterState.HvmSettings.ZeroMaleI:=1;//wylaczenie wymuszenia
       end Else begin
         TesterState.HvmSettings.ZeroMaleI:=0;//wylaczenie wymuszenia
       end;
       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 2000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(2000);

     end
     Else if(CalibrationState = CALIBRATION_STATE_APPLY_CORRECTION) Then begin
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_APPLY_CORRECTION;


       if Form1.UseOffsetNapBox.Checked Then begin
         TesterState.HvmSettings.Offset_Pom_Nap         :=      Form1.OffsetNapEdit.Value;
       end Else begin
         TesterState.HvmSettings.Offset_Pom_Nap         :=      calc_voltage_offset;
       end;
       if Form1.UseOffsetPradLBiBox.Checked Then begin
         TesterState.HvmSettings.Offset_Pom_PradL_Bi         :=      Form1.OffsetPradLBiEdit.Value;
       end Else begin
         TesterState.HvmSettings.Offset_Pom_PradL_Bi           :=      calc_current_offset_l_bi;
       end;
       if Form1.UseOffsetPradLUniBox.Checked Then begin
         TesterState.HvmSettings.Offset_Pom_PradL_Uni         :=      Form1.OffsetPradLUniEdit.Value;
       end Else begin
         TesterState.HvmSettings.Offset_Pom_PradL_Uni           :=      calc_current_offset_l_uni;
       end;
       if Form1.UseOffsetPradHBiBox.Checked Then begin
         TesterState.HvmSettings.Offset_Pom_PradH_Bi         :=      Form1.OffsetPradHBiEdit.Value;
       end Else begin
         TesterState.HvmSettings.Offset_Pom_PradH_Bi           :=      calc_current_offset_h_bi;
       end;
       if Form1.UseOffsetPradHUniBox.Checked Then begin
         TesterState.HvmSettings.Offset_Pom_PradH_Uni         :=      Form1.OffsetPradHUniEdit.Value;
       end Else begin
         TesterState.HvmSettings.Offset_Pom_PradH_Uni           :=      calc_current_offset_h_uni;
       end;
       if Form1.UseKorNapBox.Checked Then begin
         TesterState.HvmSettings.KorMul_Pom_Nap         :=      Form1.KorNapEdit.Value;
       end Else begin
         TesterState.HvmSettings.KorMul_Pom_Nap         :=      calc_voltage_corr;
       end;
       if Form1.UseKorPradHBox.Checked Then begin
         TesterState.HvmSettings.KorMul_PradH         :=      Form1.KorPradHEdit.Value;
       end Else begin
         TesterState.HvmSettings.KorMul_PradH           :=      calc_current_corr_h;
       end;
       if Form1.UseKorPradLBox.Checked Then begin
         TesterState.HvmSettings.KorMul_PradL         :=      Form1.KorPradLEdit.Value;
       end Else begin
         TesterState.HvmSettings.KorMul_PradL           :=      calc_current_corr_l;
       end;

       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 20000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(1000);
       CalibrationState := NextCalibrationState;
     end
     Else if(CalibrationState = CALIBRATION_STATE_VOLTAGE_VERIFY) Then begin
       if not Form1.VerifyBox.Checked then begin
         CalibrationState := CALIBRATION_STATE_GENERATE_REPORT;
       end Else begin


       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_VOLTAGE_VERIFY;
       DiffAvg := 0;
       DiffDiffAvg := 0;
       for i:=0 to Length(VOLTAGES)-1 Do Begin
         TesterState.TesterOutputs.glassVoltage:=VOLTAGES[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_VOLTAGE, 1);
         Sleep(100);
         if Terminated Then
           Break;
         res := AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.VoltageVerifyGrid.RowCount:=Form1.VoltageVerifyGrid.RowCount+1;
         Form1.VoltageVerifyGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.VoltageVerifyGrid.Cells[1, i+1] := IntToStr(VOLTAGES[i]*10);
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.VoltageVerifyGrid.Cells[2, i+1] := Format('%d,%.1d',[Trunc(TesterState.Status.Voltage/100), Trunc(Abs(TesterState.Status.Voltage mod 100)/10)]);
         end Else begin
           Form1.VoltageVerifyGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.VoltageVerifyGrid.Cells[3, i+1] := Format('%d,%.1d',[Trunc(TesterState.Status.VoltageRef/100), Trunc(Abs(TesterState.Status.VoltageRef mod 100)/10)]);
         end Else begin
           Form1.VoltageVerifyGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff :=  (TesterState.Status.VoltageRef- TesterState.Status.Voltage)/100;
           Form1.VoltageVerifyGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.VoltageVerifyGrid.Cells[4, i+1] := '-';
         end;
        if i>0 Then begin
            DiffDiff := Diff-StrToFloat(Form1.VoltageVerifyGrid.Cells[4, i]);
            Form1.VoltageVerifyGrid.Cells[5, i+1] := FloatToStr(DiffDiff);

         end Else begin
            Form1.VoltageVerifyGrid.Cells[5, i+1] := '-';
         end;
        Form1.VoltageVerifyGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
        DiffAvg := DiffAvg+Diff/Length(VOLTAGES);
         if i>0 Then
           DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(VOLTAGES)-1);
       end;
       if not Terminated Then begin
          Form1.VoltageVerifyGrid.RowCount:=Form1.VoltageVerifyGrid.RowCount+1;
          Form1.VoltageVerifyGrid.Cells[4, Length(VOLTAGES)+1] := FloatToStr(DiffAvg);
          Form1.VoltageVerifyGrid.Cells[5, Length(VOLTAGES)+1] := FloatToStr(DiffDiffAvg);
          CalibrationState := CALIBRATION_STATE_CURRENT_VERIFY;
       end;
       end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_CURRENT_VERIFY) Then begin

       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_SETTING_DEFAULT_VOLTAGE;
       TesterState.TesterOutputs.glassVoltage:=DEFAULT_VOLTAGE;
       SendTesterState(TYPE_TESTER_OUTPUTS);
       SetTesterState(STATE_SET_VOLTAGE, 1);
       Sleep(100);
       res := AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
       if res <> True Then begin
         Terminate;
         Break;
       end;

      DiffAvg := 0;
      DiffDiffAvg := 0;
       Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CURRENT_VERIFY;

       for i:=0 to Length(CURRENTS_VERIFY)-1 Do Begin
         TesterState.TesterOutputs.currentA:=CURRENTS_VERIFY_KOR[i];
         SendTesterState(TYPE_TESTER_OUTPUTS);
         SetTesterState(STATE_SET_CURRENT, 1);
         Sleep(100);
         if not Terminated Then
           res := AwaitTesterState(STATE_SET_CURRENT, 0, 20000);
         if res <> True Then begin
           Terminate;
           Break;
         end;
         //add new measure point
         Form1.CurrentVerifyGrid.RowCount:=Form1.CurrentVerifyGrid.RowCount+1;
         Form1.CurrentVerifyGrid.Cells[0, i+1] := IntToStr(i+1);
         Form1.CurrentVerifyGrid.Cells[1, i+1] := IntToStr(CURRENTS_VERIFY[i]);
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) Then begin
           Form1.CurrentVerifyGrid.Cells[2, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.Current/100), Abs(TesterState.Status.Current mod 100)]);
         end Else begin
           Form1.CurrentVerifyGrid.Cells[2, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Form1.CurrentVerifyGrid.Cells[3, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentRef/100), Abs(TesterState.Status.CurrentRef mod 100)]);

         end Else begin
           Form1.CurrentVerifyGrid.Cells[3, i+1] := '-';
         end;
         if TestStatusBit(STATE_HVM_EXA_CONNECTED) and TestStatusBit(STATE_HVM_REF_CONNECTED) Then begin
           Diff := (TesterState.Status.CurrentRef-TesterState.Status.Current)/100;
           Form1.CurrentVerifyGrid.Cells[4, i+1] := FloatToStr(Diff);
         end Else begin
           Form1.CurrentVerifyGrid.Cells[4, i+1] := '-';
         end;
        if i>0 Then begin
           DiffDiff := Diff-StrToFloatDef(Form1.CurrentVerifyGrid.Cells[4, i],0);
           Form1.CurrentVerifyGrid.Cells[5, i+1] := FloatToStr(DiffDiff);
        end Else begin
            Form1.CurrentVerifyGrid.Cells[5, i+1] := '-';
        end;
           Form1.CurrentVerifyGrid.Cells[6, i+1] := Format('%d,%.2d',[Trunc(TesterState.Status.CurrentGlass/100), (TesterState.Status.CurrentGlass mod 100)]);
           DiffAvg := DiffAvg+Diff/Length(CURRENTS_VERIFY);
        if i>0 Then
           DiffDiffAvg := DiffDiffAvg+DiffDiff/(Length(CURRENTS_VERIFY)-1);

       end;
       if not Terminated Then begin
          Form1.CurrentVerifyGrid.RowCount:=Form1.CurrentVerifyGrid.RowCount+1;
          Form1.CurrentVerifyGrid.Cells[4, Length(CURRENTS_VERIFY)+1] := FloatToStr(DiffAvg);
          Form1.CurrentVerifyGrid.Cells[5, Length(CURRENTS_VERIFY)+1] := FloatToStr(DiffDiffAvg);
          CalibrationState := CALIBRATION_STATE_GENERATE_REPORT;
       end;
     end
     Else if(CalibrationState = CALIBRATION_STATE_GENERATE_REPORT) Then begin
       Res := True;

       DeCodeDate (Date,YY,MM,DD);
       TesterState.HvmSettings.HVM_DataKalibr:=YY*10000+MM*100+DD;

       SendTesterState(TYPE_SETTINGS);
       SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
       if not Terminated Then
         res := AwaitTesterState(STATE_HVM_UPDATE_SETTINGS, 0, 2000);
       if res <> True Then begin
         Terminate;
         Break;
       end;
       RefreshTesterState;
       Sleep(2000);

       if not Form1.VerifyBox.Checked then begin
         Terminate;
       end Else if not Form1.GenerateReportBox.Checked then begin
         Terminate;
       end Else begin
        Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_GENERATE_REPORT;
        Form1.GenerateReport;
        Sleep(3000);
        Terminate;
       end;
     end;
  end;

  Sleep(100);
  Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_TURNING_OFF;
  calibration_running := True;
  AwaitTesterState(STATE_SET_VOLTAGE, 0, 20000);
  calibration_running := False;
  TesterState.TesterOutputs.glassVoltage:=VOLTAGE_OFF;
  SendTesterState(TYPE_TESTER_OUTPUTS);
  SetTesterState(STATE_SET_VOLTAGE, 1);

  if res Then begin
    Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_END;
    sndPlaySound('FANFARE.wav', SND_ASYNC OR SND_NODEFAULT);
  end Else begin
   if not calibration_cancelled Then begin
    Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_ERROR+' ('+IntToStr(CalibrationState)+')';
    sndPlaySound('error.wav', SND_ASYNC OR SND_NODEFAULT);
    MessageDlg(STR_CALIBRATION_ERROR+' ('+IntToStr(CalibrationState)+')', mtError, mbOKCancel, 0);
   end Else begin
    Form1.StatusBar1.Panels[1].Text:=STR_CALIBRATION_CANCELLED;
   end;
  end;

  calibration_running := False;
  Form1.Button1.Enabled := True;
  Form1.Button1.Caption := STR_CALIBRATION_START;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  SL:TStringList;
  i:Integer;
begin
  StatusBar1.Panels[0].Text := STR_DISCONNECTED;
  ShowScrollBar(CmdBox.Handle, SB_HORZ, False);
  CmdBox.StartRead(clSilver,clNavy,'>',clYellow,clNavy);
  CmdBox.TextColors(clWhite,clNavy);
  libusb.usb_init();
  libusb.usb_set_debug(3);
  SendThreadHandle := SendThread.Create(False);
  INI := TINIFile.Create('config.ini');
  DEFAULT_VOLTAGE := StrToInt(INI.ReadString('TEST_PARAMETERS','DEFAULT_VOLTAGE',''));
  MOD_NUMBER :=      StrToInt(INI.ReadString('TEST_PARAMETERS','MOD_NUMBER',''));
  SHUNT_CURRENT :=   StrToInt(INI.ReadString('TEST_PARAMETERS','SHUNT_CURRENT',''));
  SHUNT_VOLTAGE :=   StrToInt(INI.ReadString('TEST_PARAMETERS','SHUNT_VOLTAGE',''));
  HARD_VER :=        StrToInt(INI.ReadString('TEST_PARAMETERS','HARD_VER',''));
  ZERO_I :=          StrToInt(INI.ReadString('TEST_PARAMETERS','ZERO_I',''));
  INTERVAL :=        StrToInt(INI.ReadString('TEST_PARAMETERS','INTERVAL',''));
  PROD_DATE :=        StrToInt(INI.ReadString('TEST_PARAMETERS','PROD_DATE',''));

  PROGRAM_FLASH :=   StrToInt(INI.ReadString('TEST_PARAMETERS','PROGRAM_FLASH',''));
  CALIB_VOLTAGE :=  StrToInt(INI.ReadString('TEST_PARAMETERS','CALIB_VOLTAGE',''));
  CALIB_CURRENT :=  StrToInt(INI.ReadString('TEST_PARAMETERS','CALIB_CURRENT',''));
  VERIFY :=          StrToInt(INI.ReadString('TEST_PARAMETERS','VERIFY',''));
  GENERATE_REPORT := StrToInt(INI.ReadString('TEST_PARAMETERS','GENERATE_REPORT',''));

  ModNumberEdit.Value:=MOD_NUMBER;
  ShuntCurrentEdit.Value:=SHUNT_CURRENT;
  ShuntVoltageEdit.Value:=SHUNT_VOLTAGE;
  HardVerEdit.Value := HARD_VER;
  ProdDateEdit.Value := PROD_DATE;
  if ZERO_I <> 0 Then
    ZeroMaleICheckbox.Checked:=True;
  if PROGRAM_FLASH <> 0 Then
    ProgramFlashBox.Checked:=True;
  if CALIB_VOLTAGE <> 0 Then
    CalibVoltageBox.Checked:=True;
  if CALIB_CURRENT <> 0 Then
    CalibCurrentBox.Checked:=True;
  if VERIFY <> 0 Then
    VerifyBox.Checked:=True;
  if GENERATE_REPORT <> 0 Then
    GenerateReportBox.Checked:=True;
  if INTERVAL = 0 Then begin
    RadioButton1.Checked:=True;
  end
  Else if INTERVAL = 1 then begin
    RadioButton2.Checked:=True;
  end
  Else if INTERVAL = 2 then begin
    RadioButton3.Checked:=True;
  end;
  SL := TStringList.Create;
  try
    SL.StrictDelimiter := True;
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','VOLTAGES','');
    SetLength(VOLTAGES, SL.Count);
    for i := 0 to SL.Count - 1 do
      VOLTAGES[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_L_UNI','');
    SetLength(CURRENTS_L_UNI, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_L_UNI[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_L_UNI_KOR','');
    SetLength(CURRENTS_L_UNI_KOR, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_L_UNI_KOR[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_L_BI','');
    SetLength(CURRENTS_L_BI, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_L_BI[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_L_BI_KOR','');
    SetLength(CURRENTS_L_BI_KOR, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_L_BI_KOR[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_H_UNI','');
    SetLength(CURRENTS_H_UNI, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_H_UNI[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_H_UNI_KOR','');
    SetLength(CURRENTS_H_UNI_KOR, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_H_UNI_KOR[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_H_BI','');
    SetLength(CURRENTS_H_BI, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_H_BI[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_H_BI_KOR','');
    SetLength(CURRENTS_H_BI_KOR, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_H_BI_KOR[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_VERIFY','');
    SetLength(CURRENTS_VERIFY, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_VERIFY[i] := StrToInt(Trim(SL[i]));
    SL.CommaText :=  INI.ReadString('TEST_PARAMETERS','CURRENTS_VERIFY_KOR','');
    SetLength(CURRENTS_VERIFY_KOR, SL.Count);
    for i := 0 to SL.Count - 1 do
      CURRENTS_VERIFY_KOR[i] := StrToInt(Trim(SL[i]));
  finally
    SL.Free;
  end;

end;

procedure TForm1.HardVerEditEditingDone(Sender: TObject);
begin
  HARD_VER := HardVerEdit.Value;
  INI.WriteInteger('TEST_PARAMETERS','HARD_VER', HARD_VER);
end;

procedure TForm1.MenuItem2Click(Sender: TObject);
begin
  RefreshTesterState;
end;

procedure TForm1.ModNumberEditChange(Sender: TObject);
begin

end;

procedure TForm1.ModNumberEditEditingDone(Sender: TObject);
begin
  MOD_NUMBER := ModNumberEdit.Value;
  INI.WriteInteger('TEST_PARAMETERS','MOD_NUMBER', MOD_NUMBER);
end;

procedure TForm1.CmdBoxInput(ACmdBox: TCmdBox; Input: string);
var
  dataout:Array[0..MAX_PACKET_SIZE] of Char;
  i:Integer;
begin
  If(Length(Input) < MAX_PACKET_SIZE) Then begin
    If Length(Input) > 0 then begin
      for i:=1 to Length(Input) Do begin
        dataout[i-1] := Input[i];
      end;
    end Else begin
      i := 0;
    end;
    dataout[i] := chr($0A);
    if(not(dev_handle = nil)) Then begin
      libusb.usb_bulk_write(dev_handle, BULK_CHAR_OUT_EP, dataout, i+1,-1);
    end;
  end;
  ACmdBox.StartRead(clSilver,clNavy,'>',clYellow,clNavy);

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if not calibration_running Then begin
    CalibrationThreadHandle := CalibrationThread.Create(False);
    calibration_running := True;
    Button1.Caption := STR_CALIBRATION_CANCEL;
  end
  Else begin
    Button1.Enabled := False;
    CalibrationThreadHandle.Terminate;
    calibration_running := False;
    calibration_cancelled := True;
    Button1.Caption := STR_CALIBRATION_START;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  GenerateReport;
end;

procedure TForm1.CalibCurrentBoxChange(Sender: TObject);
begin
    if CalibCurrentBox.Checked Then begin
    CALIB_CURRENT := 1;
  end
  Else begin
    CALIB_CURRENT := 0;
  end;
  INI.WriteInteger('TEST_PARAMETERS','CALIB_CURRENT', CALIB_CURRENT);
end;

procedure TForm1.CalibVoltageBoxChange(Sender: TObject);
begin
  if CalibVoltageBox.Checked Then begin
    CALIB_VOLTAGE := 1;
  end
  Else begin
    CALIB_VOLTAGE := 0;
  end;
  INI.WriteInteger('TEST_PARAMETERS','CALIB_VOLTAGE', CALIB_VOLTAGE);
end;

procedure TForm1.CmdBoxClick(Sender: TObject);
begin

end;

procedure TForm1.GenerateReportBoxChange(Sender: TObject);
begin
  if GenerateReportBox.Checked Then begin
    GENERATE_REPORT := 1;
  end
  Else begin
    GENERATE_REPORT := 0;
  end;
  INI.WriteInteger('TEST_PARAMETERS','GENERATE_REPORT', GENERATE_REPORT);
end;

procedure TForm1.GlassSetBtnClick(Sender: TObject);
begin
  TesterState.TesterOutputs.glassVoltage:=Round(GlassVoltageEdit.Value*100);
  SendTesterState(TYPE_TESTER_OUTPUTS);
  SetTesterState(STATE_SET_VOLTAGE, 1);
end;

function TForm1.OpenUsb:Boolean;
var
  res:Integer;
begin
  result := False;
  dev_handle := libusb.usb_find_device(USB_DEV_VID,USB_DEV_PID,0);
  if(dev_handle = nil) Then  begin
    Exit(result);
  end;
  res := libusb.usb_set_configuration(dev_handle,1);
  if(res <> 0) Then begin
    Exit(result);
  end;
  res := libusb.usb_claim_interface(dev_handle,0);
  if(res <> 0) Then  begin
    Exit(result);
  end;
  if(res = 0) Then begin
    RecvThreadHandle := RecvThread.Create(False);
    StatusBar1.Panels[0].Text := STR_CONNECTED;
    TrayIconDisconnected.Visible := False;
    TrayIconConnected.Visible := True;
    result := True;
    Button1.Enabled := True;
    GlassSetBtn.Enabled := False;
  end;
end;

procedure TForm1.CloseUsb;
begin
  RecvThreadHandle.Terminate;
  if(calibration_running) Then begin
    CalibrationThreadHandle.Terminate;
    calibration_running := False;
    Button1.Caption := STR_CALIBRATION_START;
  end;
  Button1.Enabled := False;
  if(dev_handle <> nil) Then
    libusb.usb_close(dev_handle);
  StatusBar1.Panels[0].Text := STR_DISCONNECTED;
  TrayIconDisconnected.Visible := True;
  TrayIconConnected.Visible := False;

  Form1.VoltageLabel.Caption := '-';
  Form1.CurrentLabel.Caption := '-';
  Form1.VoltageRefLabel.Caption := '-';
  Form1.CurrentRefLabel.Caption := '-';
  Form1.VoltageGlass.Caption := '-';
  Form1.CurrentGlass.Caption := '-';
end;

procedure TForm1.ProdDateEditEditingDone(Sender: TObject);
begin
  PROD_DATE := ModNumberEdit.Value;
  INI.WriteInteger('TEST_PARAMETERS','PROD_DATE', PROD_DATE);
end;

procedure TForm1.ProgramFlashBoxChange(Sender: TObject);
begin
  if ProgramFlashBox.Checked Then begin
    PROGRAM_FLASH := 1;
  end
  Else begin
    PROGRAM_FLASH := 0;
  end;
  INI.WriteInteger('TEST_PARAMETERS','PROGRAM_FLASH', PROGRAM_FLASH);
end;

procedure TForm1.RadioButton1Change(Sender: TObject);
begin
  INTERVAL := 0;
  INI.WriteInteger('TEST_PARAMETERS','INTERVAL', INTERVAL);
end;

procedure TForm1.RadioButton2Change(Sender: TObject);
begin
  INTERVAL := 1;
  INI.WriteInteger('TEST_PARAMETERS','INTERVAL', INTERVAL);
end;

procedure TForm1.RadioButton3Change(Sender: TObject);
begin
  INTERVAL := 2;
  INI.WriteInteger('TEST_PARAMETERS','INTERVAL', INTERVAL);
end;

procedure TForm1.ShuntCurrentEditEditingDone(Sender: TObject);
begin
  SHUNT_CURRENT := ShuntCurrentEdit.Value;
  INI.WriteInteger('TEST_PARAMETERS','SHUNT_CURRENT', SHUNT_CURRENT);
end;

procedure TForm1.ShuntVoltageEditEditingDone(Sender: TObject);
begin
  SHUNT_VOLTAGE := ShuntVoltageEdit.Value;
  INI.WriteInteger('TEST_PARAMETERS','SHUNT_VOLTAGE', SHUNT_VOLTAGE);
end;


procedure SendTesterState(StatusValue:Byte);
var
  dataout: Array[0..MAX_PACKET_SIZE] of Char;
  dataSize:Integer;
begin
  dataout[0] := chr(StatusValue);
  if (StatusValue = TYPE_STATUS) Then begin
    dataSize := SizeOf(TesterState.Status.State);
    Move(TesterState.Status.State, dataout[1], dataSize);
  end
  Else if (StatusValue = TYPE_SETTINGS) Then begin
    dataSize := SizeOf(TesterState.HvmSettings);
    Move(TesterState.HvmSettings, dataout[1], dataSize);
  end
  Else if (StatusValue = TYPE_MEAS) Then begin
    dataSize := SizeOf(TesterState.HvmMeas);
    Move(TesterState.HvmMeas, dataout[1], dataSize);
  end
  Else if (StatusValue = TYPE_INFO) Then begin
    dataSize := SizeOf(TesterState.HvmInfo);
    Move(TesterState.HvmInfo, dataout[1], dataSize);
  end
  Else if (StatusValue = TYPE_EVENT) Then begin
    dataSize := SizeOf(TesterState.HvmEvent);
    Move(TesterState.HvmEvent, dataout[1], dataSize);
  end
  Else if (StatusValue = TYPE_TESTER_OUTPUTS) Then begin
    dataSize := SizeOf(TesterState.TesterOutputs);
    Move(TesterState.TesterOutputs, dataout[1], dataSize);
  end;
  if(not(dev_handle = nil)) Then begin
    libusb.usb_interrupt_write(dev_handle, INTERRUPT_OUT_EP, dataout, dataSize+1,-1);
  end;
end;

procedure SetTesterState(StatusBit:Byte; State:Integer);
begin
  if(State > 0) Then begin
    TesterState.Status.State := TesterState.Status.State or (1 shl StatusBit);
  end Else begin
    TesterState.Status.State := TesterState.Status.State and not(1 shl StatusBit);
  end;
  SendTesterState(TYPE_STATUS);
end;

function AwaitTesterState(StatusBit:Byte; State,timeout:Integer):Boolean;
begin
   while (TesterState.Status.State and (1 shl StatusBit) <> State) Do begin
     if(TesterState.Status.State and (1 shl STATE_HVM_ERROR) > 0) Then begin
       SetTesterState(STATE_HVM_ERROR, 0);
       SetTesterState(StatusBit, 0);
       Exit(False);
     end;
     if (not usb_connected) or (not calibration_running) Then begin
       Exit(False);
     end;
     Sleep(10);
     timeout := timeout-10;
     if timeout = 0 Then begin
       SetTesterState(StatusBit, 0);
       Exit(False);
   end;
  end;
  result := True;
end;

procedure RequestTesterState(StatusValue:Byte);
var
  dataout:Array[0..MAX_PACKET_SIZE] of Char;
begin
  dataout[0] := chr(StatusValue);
  if(not(dev_handle = nil)) Then begin
    libusb.usb_interrupt_write(dev_handle, INTERRUPT_OUT_EP, dataout, 1,-1);
  end;
end;

procedure RefreshTesterState;
begin
  data_initialize := True;
end;

{procedure TForm1.StringGrid1SelectCell(Sender: TObject; aCol, aRow: Integer;
  var CanSelect: Boolean);
begin
  if (aCol+1) mod 2 > 0 Then begin
    CanSelect := False;
  end;
end; }

procedure TForm1.StringGrid1ValidateEntry(sender: TObject; aCol, aRow: Integer;
  const OldValue: string; var NewValue: String);
var
  dummy:Integer;
  res:Boolean;
begin
  if not TryStrToInt(NewValue, dummy) Then begin
    NewValue := OldValue;
    Exit;
  end;
    //settings
    TesterState.HvmSettings.NrModHVM               :=      StrToInt(Form1.StringGrid1.Cells[1,1]   );
    TesterState.HvmSettings.Rezerwa                :=      StrToInt(Form1.StringGrid1.Cells[1,2]   );
    TesterState.HvmSettings.HardVer                :=      StrToInt(Form1.StringGrid1.Cells[1,3]   );
    TesterState.HvmSettings.ZeroMaleI              :=      StrToInt(Form1.StringGrid1.Cells[1,4]   );
    TesterState.HvmSettings.KorMul_PradL            :=      StrToInt(Form1.StringGrid1.Cells[1,5]   );
    TesterState.HvmSettings.TypBocz_Prad           :=      StrToInt(Form1.StringGrid1.Cells[1,6]   );
    TesterState.HvmSettings.TypBocz_Nap            :=      StrToInt(Form1.StringGrid1.Cells[1,7]   );
    TesterState.HvmSettings.Interwal               :=      StrToInt(Form1.StringGrid1.Cells[1,8]   );
    TesterState.HvmSettings.Offset_Pom_Nap         :=      StrToInt(Form1.StringGrid1.Cells[1,9]   );
    TesterState.HvmSettings.Offset_Pom_PradL_Bi    :=      StrToInt(Form1.StringGrid1.Cells[1,10]  );
    TesterState.HvmSettings.Offset_Pom_PradL_Uni   :=      StrToInt(Form1.StringGrid1.Cells[1,11]  );
    TesterState.HvmSettings.Offset_Pom_PradH_Bi    :=      StrToInt(Form1.StringGrid1.Cells[1,12]  );
    TesterState.HvmSettings.Offset_Pom_PradH_Uni   :=      StrToInt(Form1.StringGrid1.Cells[1,13]  );
    TesterState.HvmSettings.KorMul_Pom_Nap         :=      StrToInt(Form1.StringGrid1.Cells[1,14]  );
    TesterState.HvmSettings.KorMul_PradH           :=      StrToInt(Form1.StringGrid1.Cells[1,15]  );
    TesterState.HvmSettings.Hvm_DataKalibr         :=      StrToIntDef(Form1.StringGrid1.Cells[1,16], 0  );
    TesterState.HvmSettings.Hvm_DataProd           :=      StrToIntDef(Form1.StringGrid1.Cells[1,17], 0  );
    TesterState.HvmSettings.EE_CrcKalibr           :=      StrToInt(Form1.StringGrid1.Cells[1,18]  );
  //meas
    {TesterState.HvmMeas.voltage      := StrToInt(Form1.StringGrid1.Cells[3,1]   );
    TesterState.HvmMeas.voltage_r    := StrToInt(Form1.StringGrid1.Cells[3,2]   );
    TesterState.HvmMeas.current      := StrToInt(Form1.StringGrid1.Cells[3,3]   );
    TesterState.HvmMeas.current_r    := StrToInt(Form1.StringGrid1.Cells[3,4]   );
    TesterState.HvmMeas.energyIn     := StrToInt(Form1.StringGrid1.Cells[3,5]   );
    TesterState.HvmMeas.energyIn_r   := StrToInt(Form1.StringGrid1.Cells[3,6]   );
    TesterState.HvmMeas.energyOut    := StrToInt(Form1.StringGrid1.Cells[3,7]   );
    TesterState.HvmMeas.energyOut_r  := StrToInt(Form1.StringGrid1.Cells[3,8]   );
    TesterState.HvmMeas.time         := StrToInt(Form1.StringGrid1.Cells[3,9]   );
    TesterState.HvmMeas.eventIndex   := StrToInt(Form1.StringGrid1.Cells[3,10]  );
    TesterState.HvmMeas.errStat      := StrToInt(Form1.StringGrid1.Cells[3,11]  );
    TesterState.HvmMeas.energyAvg    := StrToInt(Form1.StringGrid1.Cells[3,12]  );
    TesterState.HvmMeas.energyAvg_r  := StrToInt(Form1.StringGrid1.Cells[3,13]  );
  //info
    TesterState.HvmInfo.HardVer          := StrToInt(Form1.StringGrid1.Cells[5,1]  );
    TesterState.HvmInfo.SoftVer          := StrToInt(Form1.StringGrid1.Cells[5,2]  );
    TesterState.HvmInfo.RPomIU           := StrToInt(Form1.StringGrid1.Cells[5,3]  );
    TesterState.HvmInfo.NrHvm            := StrToInt(Form1.StringGrid1.Cells[5,4]  );
    TesterState.HvmInfo.DTContrMetr      := StrToInt(Form1.StringGrid1.Cells[5,5]  );
    TesterState.HvmInfo.TypBocz_PradL    := StrToInt(Form1.StringGrid1.Cells[5,6]  );
    TesterState.HvmInfo.TypBocz_PradH    := StrToInt(Form1.StringGrid1.Cells[5,7]  );
    TesterState.HvmInfo.TypBocz_Nap      := StrToInt(Form1.StringGrid1.Cells[5,8]  );
    TesterState.HvmInfo.DTProd           := StrToInt(Form1.StringGrid1.Cells[5,9]  );
    TesterState.HvmInfo.HvmRstStatusErr  := StrToInt(Form1.StringGrid1.Cells[5,10] );
    TesterState.HvmInfo.HvmRstStatusTmp  := StrToInt(Form1.StringGrid1.Cells[5,11] );
    TesterState.HvmInfo.Interval         := StrToInt(Form1.StringGrid1.Cells[5,12] );
  //event
    TesterState.HvmEvent.hvmIndex      :=  StrToInt(Form1.StringGrid1.Cells[7,1] );
    TesterState.HvmEvent.eventType     :=  StrToInt(Form1.StringGrid1.Cells[7,2] );
    TesterState.HvmEvent.time          :=  StrToInt(Form1.StringGrid1.Cells[7,3] );
    TesterState.HvmEvent.energyIn      :=  StrToInt(Form1.StringGrid1.Cells[7,4] );
    TesterState.HvmEvent.energyIn_r    :=  StrToInt(Form1.StringGrid1.Cells[7,5] );
    TesterState.HvmEvent.energyOut     :=  StrToInt(Form1.StringGrid1.Cells[7,6] );
    TesterState.HvmEvent.energyOut_r   :=  StrToInt(Form1.StringGrid1.Cells[7,7] );
    TesterState.HvmEvent.eventIndex    :=  StrToInt(Form1.StringGrid1.Cells[7,8] );
    TesterState.HvmEvent.reserve       :=  StrToInt(Form1.StringGrid1.Cells[7,9] );
    TesterState.HvmEvent.hvmStat       :=  StrToInt(Form1.StringGrid1.Cells[7,10]);
    TesterState.HvmEvent.pos[0]        :=  StrToInt(Form1.StringGrid1.Cells[7,11]);
    TesterState.HvmEvent.eventCrc      :=  StrToInt(Form1.StringGrid1.Cells[7,12]);    }

    SendTesterState(TYPE_SETTINGS);

    SetTesterState(STATE_HVM_UPDATE_SETTINGS, 1);
    RefreshTesterState;
end;

procedure TForm1.VerifyBoxChange(Sender: TObject);
begin
  if VerifyBox.Checked Then begin
    VERIFY := 1;
  end
  Else begin
    VERIFY := 0;
  end;
  INI.WriteInteger('TEST_PARAMETERS','VERIFY', VERIFY);
end;

procedure TForm1.ZeroMaleICheckboxChange(Sender: TObject);
begin
  if ZeroMaleICheckbox.Checked Then begin
    ZERO_I := 1;
  end
  Else begin
    ZERO_I := 0;
  end;
  INI.WriteInteger('TEST_PARAMETERS','ZERO_I', ZERO_I);
end;

procedure UpdateLocalHvmSettings;
begin
    TesterState.HvmSettings.NrModHVM               :=      StrToInt(Form1.StringGrid1.Cells[1,1]   );
    TesterState.HvmSettings.HardVer                :=      StrToInt(Form1.StringGrid1.Cells[1,2]   );
    TesterState.HvmSettings.ZeroMaleI              :=      StrToInt(Form1.StringGrid1.Cells[1,3]   );
    TesterState.HvmSettings.KorMul_PradL            :=      StrToInt(Form1.StringGrid1.Cells[1,5]   );
    TesterState.HvmSettings.TypBocz_Prad           :=      StrToInt(Form1.StringGrid1.Cells[1,6]   );
    TesterState.HvmSettings.TypBocz_Nap            :=      StrToInt(Form1.StringGrid1.Cells[1,7]   );
    TesterState.HvmSettings.Interwal               :=      StrToInt(Form1.StringGrid1.Cells[1,8]   );
    TesterState.HvmSettings.Offset_Pom_Nap         :=      StrToInt(Form1.StringGrid1.Cells[1,9]   );
    TesterState.HvmSettings.Offset_Pom_PradL_Bi    :=      StrToInt(Form1.StringGrid1.Cells[1,10]  );
    TesterState.HvmSettings.Offset_Pom_PradL_Uni   :=      StrToInt(Form1.StringGrid1.Cells[1,11]  );
    TesterState.HvmSettings.Offset_Pom_PradH_Bi    :=      StrToInt(Form1.StringGrid1.Cells[1,12]  );
    TesterState.HvmSettings.Offset_Pom_PradH_Uni   :=      StrToInt(Form1.StringGrid1.Cells[1,13]  );
    TesterState.HvmSettings.KorMul_Pom_Nap         :=      StrToInt(Form1.StringGrid1.Cells[1,14]  );
    TesterState.HvmSettings.KorMul_PradH           :=      StrToInt(Form1.StringGrid1.Cells[1,15]  );
    TesterState.HvmSettings.Hvm_DataKalibr         :=      StrToInt(Form1.StringGrid1.Cells[1,16]  );
end;

function TestStatusBit(Bit:Byte):Boolean;
begin
  if (TesterState.Status.State and (1 shl Bit)) > 0 Then begin
    Result:=True;
  end
  Else begin
    Result := False;
  end;

end;

procedure TForm1.GenerateReport;
var
  ReportPage:TPRPage;
  ReportLayoutPanel:TPRLayoutPanel;
  ReportLabel,Nastawy1Label,Voltage1Label,Current1Label:TPRLabel;
  Nastawy0Text,Nastawy1Text:TPRText;
  Voltage0Text,Voltage1Text,Voltage2Text,Voltage3Text,Voltage4Text,Voltage5Text:TPRText;
  Current0Text,Current1Text,Current2Text,Current3Text,Current4Text,Current5Text:TPRText;
begin
  ReportPDF.FileName:='FastReport_'+IntToStr(MOD_NUMBER)+'.pdf';
  ReportPDF.BeginDoc;

  ReportPage := TPRPage.Create(Self);
  ReportPage.Parent := Self;
  ReportPage.MarginTop := 32;
  ReportPage.MarginLeft := 32;
  ReportPage.MarginRight := 32;
  ReportPage.MarginBottom := 32;

  ReportLayoutPanel := TPRLayoutPanel.Create(Self);
  ReportLayoutPanel.Parent := ReportPage;

  ReportLabel := TPRLabel.Create(Self);
  ReportLabel.Top := 50;
  ReportLabel.FontSize := 20;
  ReportLabel.FontBold := True;
  ReportLabel.Parent := ReportLayoutPanel;
  ReportLabel.Alignment:=taCenter;
  ReportLabel.Width := ReportPage.Width;
  ReportLabel.Height := ReportPage.Height;
  ReportLabel.Caption := 'RAPORT Z KALIBRACJI EM3000 WN';

  Nastawy1Label := TPRLabel.Create(Self);
  Nastawy1Label.Top := 80;
  Nastawy1Label.FontSize := 14;
  Nastawy1Label.FontBold := True;
  Nastawy1Label.Parent := ReportLayoutPanel;
  Nastawy1Label.Alignment:=taCenter;
  Nastawy1Label.Width := ReportPage.Width;
  Nastawy1Label.Height := ReportPage.Height;
  Nastawy1Label.Caption := 'Nastawy kalibracyjne';

  Nastawy0Text := TPRText.Create(Self);
  Nastawy0Text.FontSize:=10;
  Nastawy0Text.Top:=100;
  Nastawy0Text.Left:=60;
  Nastawy0Text.Width := ReportPage.Width;
  Nastawy0Text.Height:= ReportPage.Height;
  Nastawy0Text.Parent := ReportLayoutPanel;
  Nastawy0Text.Lines:=StringGrid1.Cols[0];
  Nastawy1Text := TPRText.Create(Self);
  Nastawy1Text.FontSize:=10;
  Nastawy1Text.Top:=100;
  Nastawy1Text.Left:=180;
  Nastawy1Text.Width := ReportPage.Width;
  Nastawy1Text.Height:= ReportPage.Height;
  Nastawy1Text.Parent := ReportLayoutPanel;
  Nastawy1Text.Lines:=StringGrid1.Cols[1];

  Voltage1Label := TPRLabel.Create(Self);
  Voltage1Label.Top := 380;
  Voltage1Label.FontSize := 14;
  Voltage1Label.FontBold := True;
  Voltage1Label.Parent := ReportLayoutPanel;
  Voltage1Label.Alignment:=taCenter;
  Voltage1Label.Width := ReportPage.Width;
  Voltage1Label.Height := ReportPage.Height;
  Voltage1Label.Caption := 'Wynik weryfikacji pomiarow napiecia';

  Voltage0Text := TPRText.Create(Self);
  Voltage0Text.FontSize:=10;
  Voltage0Text.Top:=400;
  Voltage0Text.Left:=60;
  Voltage0Text.Width := ReportPage.Width;
  Voltage0Text.Height:= ReportPage.Height;
  Voltage0Text.Parent := ReportLayoutPanel;
  Voltage0Text.Lines:=VoltageVerifyGrid.Cols[0];
  Voltage1Text := TPRText.Create(Self);
  Voltage1Text.FontSize:=10;
  Voltage1Text.Top:=400;
  Voltage1Text.Left:=140;
  Voltage1Text.Width := ReportPage.Width;
  Voltage1Text.Height:= ReportPage.Height;
  Voltage1Text.Parent := ReportLayoutPanel;
  Voltage1Text.Lines:=VoltageVerifyGrid.Cols[1];
  Voltage2Text := TPRText.Create(Self);
  Voltage2Text.FontSize:=10;
  Voltage2Text.Top:=400;
  Voltage2Text.Left:=220;
  Voltage2Text.Width := ReportPage.Width;
  Voltage2Text.Height:= ReportPage.Height;
  Voltage2Text.Parent := ReportLayoutPanel;
  Voltage2Text.Lines:=VoltageVerifyGrid.Cols[2];
  Voltage3Text := TPRText.Create(Self);
  Voltage3Text.FontSize:=10;
  Voltage3Text.Top:=400;
  Voltage3Text.Left:=300;
  Voltage3Text.Width := ReportPage.Width;
  Voltage3Text.Height:= ReportPage.Height;
  Voltage3Text.Parent := ReportLayoutPanel;
  Voltage3Text.Lines:=VoltageVerifyGrid.Cols[3];
  Voltage4Text := TPRText.Create(Self);
  Voltage4Text.FontSize:=10;
  Voltage4Text.Top:=400;
  Voltage4Text.Left:=380;
  Voltage4Text.Width := ReportPage.Width;
  Voltage4Text.Height:= ReportPage.Height;
  Voltage4Text.Parent := ReportLayoutPanel;
  Voltage4Text.Lines:=VoltageVerifyGrid.Cols[4];
  Voltage5Text := TPRText.Create(Self);
  Voltage5Text.FontSize:=10;
  Voltage5Text.Top:=400;
  Voltage5Text.Left:=460;
  Voltage5Text.Width := ReportPage.Width;
  Voltage5Text.Height:= ReportPage.Height;
  Voltage5Text.Parent := ReportLayoutPanel;
  Voltage5Text.Lines:=VoltageVerifyGrid.Cols[5];

  Current1Label := TPRLabel.Create(Self);
  Current1Label.Top := 530;
  Current1Label.FontSize := 14;
  Current1Label.FontBold := True;
  Current1Label.Parent := ReportLayoutPanel;
  Current1Label.Alignment:=taCenter;
  Current1Label.Width := ReportPage.Width;
  Current1Label.Height := ReportPage.Height;
  Current1Label.Caption := 'Wynik weryfikacji pomiarow pradu';

  Current0Text := TPRText.Create(Self);
  Current0Text.FontSize:=10;
  Current0Text.Top:=550;
  Current0Text.Left:=60;
  Current0Text.Width := ReportPage.Width;
  Current0Text.Height:= ReportPage.Height;
  Current0Text.Parent := ReportLayoutPanel;
  Current0Text.Lines:=CurrentVerifyGrid.Cols[0];
  Current1Text := TPRText.Create(Self);
  Current1Text.FontSize:=10;
  Current1Text.Top:=550;
  Current1Text.Left:=140;
  Current1Text.Width := ReportPage.Width;
  Current1Text.Height:= ReportPage.Height;
  Current1Text.Parent := ReportLayoutPanel;
  Current1Text.Lines:=CurrentVerifyGrid.Cols[1];
  Current2Text := TPRText.Create(Self);
  Current2Text.FontSize:=10;
  Current2Text.Top:=550;
  Current2Text.Left:=220;
  Current2Text.Width := ReportPage.Width;
  Current2Text.Height:= ReportPage.Height;
  Current2Text.Parent := ReportLayoutPanel;
  Current2Text.Lines:=CurrentVerifyGrid.Cols[2];
  Current3Text := TPRText.Create(Self);
  Current3Text.FontSize:=10;
  Current3Text.Top:=550;
  Current3Text.Left:=300;
  Current3Text.Width := ReportPage.Width;
  Current3Text.Height:= ReportPage.Height;
  Current3Text.Parent := ReportLayoutPanel;
  Current3Text.Lines:=CurrentVerifyGrid.Cols[3];
  Current4Text := TPRText.Create(Self);
  Current4Text.FontSize:=10;
  Current4Text.Top:=550;
  Current4Text.Left:=380;
  Current4Text.Width := ReportPage.Width;
  Current4Text.Height:= ReportPage.Height;
  Current4Text.Parent := ReportLayoutPanel;
  Current4Text.Lines:=CurrentVerifyGrid.Cols[4];
  Current5Text := TPRText.Create(Self);
  Current5Text.FontSize:=10;
  Current5Text.Top:=550;
  Current5Text.Left:=460;
  Current5Text.Width := ReportPage.Width;
  Current5Text.Height:= ReportPage.Height;
  Current5Text.Parent := ReportLayoutPanel;
  Current5Text.Lines:=CurrentVerifyGrid.Cols[5];

  ReportPDF.Print(ReportPage);
  ReportPDF.EndDoc;
  ReportPage.Free;
end;

end.

